Pure Functions

Question Click to View Answer

Is the following function pure? Explain.

def add(x: Int, y: Int): Int = {
  x + y
}

The add function does not have any side effects, so it is pure. Examples of side effects from Functional Programming in Scala:

  • Reassigning a variable
  • Modifying a data structure in place
  • Setting a field on an object
  • Throwing an exception or halting with an error Printing to the console or reading user input Reading from or writing to a file
  • Drawing on the screen

Is the following function pure? Explain.

def changeStuff: Unit = {
  x = x + 10
}

The changeStuff function isn't pure because it reassigns a variable (variable reassignment is a side effect).

var x = 33
changeStuff
// x is now 43

Is the following function pure? Explain.

def funify: String = {
  word.append("Fun!").toString
}

The funify function isn't pure because it modifies a value in place (variable reassignment is a side effect).

var word = new StringBuilder("Beach")
funify
// word is now BeachFun!
funify
// word is now BeachFun!Fun!

Is the following changeName function pure? Explain.

class Person(n: String) {
  var name = n
}

def changeName(p: Person): Unit = {
  p.name = "cathy"
}

var bob = new Person("bob")
changeName(bob)

The changeName function is not pure because it sets a field in an object. The changeName changes the state of an object, so the function has side effects.

Is the following function pure? Explain.

def fullName(firstName: String, lastName: String): String = {
  s"$firstName $lastName"
}

fullName("Ricky", "Bobby")

The fullName function is pure. It takes two string inputs and returns a string. The state of the program is not changed by the function, so the function doesn't have any side effects.

Is the following function pure? Explain.

def loco: Unit = {
  println("toma 4loco!")
}

loco

The loco function prints to the screen which is a side effect, so the function is not pure.

Is the following function pure? Explain.

import java.io._

def shaggy: Unit = {
  val path = s"${System.getProperty("user.home")}/Desktop/mr_lover.txt"
  val file = new File(path)
  file.createNewFile();
}

The shaggy function creates a file on the user's Desktop, so it is not pure.

Is the following function pure? Explain.

def divide(numerator: Double, denominator: Double): Double = {
  if (denominator == 0)
    throw new IllegalArgumentException("The denominator can't be zero")
  else
    numerator / denominator
}

The divide function isn't pure because it throws an exception if the denominator is zero.