Skip to content

Instantly share code, notes, and snippets.

@ecamellini
Last active May 15, 2017 16:24
Show Gist options
  • Save ecamellini/f72aef6f401a86335393006a850298be to your computer and use it in GitHub Desktop.
Save ecamellini/f72aef6f401a86335393006a850298be to your computer and use it in GitHub Desktop.
Evaluation strategies: call-by-name and call-by-value

call-by-value

The interpreter evaluates all the arguments before evaluating the function itself (i.e., before rewriting the function application).

It has the advantage that every argument is evaluated only once.

call-by-name

The interpreter passes the arguments "as they are" to the function: this means that they are evaluated every time they are used inside it.

It has the advantage that a function argument is not evaluated if the corresponding parameter is unused in the evaluation of the function body.

Example

  1. Let's define a scala method with side effects:
def helloInt(i: Int): Int = {
   println(s"Hello, I am an Int with value $i")
   i
}
  1. Let's define the same method with two different strategies:
def firstByValue(a: Int, b: Int): Int = a // call-by-value (default)
def firstByName(a: => Int, b: => Int): Int = a // call-by-name

The output in the scala REPL will be the following:

scala> firstByValue(helloInt(1), helloInt(2))
Hello, I am an Int with value 1
Hello, I am an Int with value 2
res11: Int = 1

scala> firstByName(helloInt(1), helloInt(2))
Hello, I am an Int with value 1
res12: Int = 1

You can see that in the call-by-name case the second argument is not evualuated because it is never used.

However, if an arguments is used two times, for example, it is evaluated twice. This can be seen by running the following in the scala REPL:

scala> def square(i: Int): Int = i * i
square: (i: Int)Int

scala> square(helloInt(1))
Hello, I am an Int with value 1
res15: Int = 1

scala> def square(i: => Int): Int = i * i
square: (i: => Int)Int

scala> square(helloInt(1))
Hello, I am an Int with value 1
Hello, I am an Int with value 1
res16: Int = 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment