Showing posts with label call by name. Show all posts
Showing posts with label call by name. Show all posts

Thursday, November 7, 2013

Evaluation strategies in Scala

What evaluation strategy does Scala follows? OR How does call by name and call by value evaluation strategies supported in Scala?

I would suggest reading wiki for understanding basics of evaluation strategies (http://en.wikipedia.org/wiki/Evaluation_strategy), specifically call by name and call by value, since both of these are supported in Scala. Below are the extracts which I found most useful:
Call by value
In call-by-value, the argument expression is evaluated, and the resulting value is bound to the corresponding variable in the function (frequently by copying the value into a new memory region). If the function or procedure is able to assign values to its parameters, only its local copy is assigned — that is, anything passed into a function call is unchanged in the caller's scope when the function returns.
Call by name
In call-by-name evaluation, the arguments to a function are not evaluated before the function is called — rather, they are substituted directly into the function body (using capture-avoiding substitution) and then left to be evaluated whenever they appear in the function. If an argument is not used in the function body, the argument is never evaluated; if it is used several times, it is re-evaluated each time it appears.
To understand this in Scala context, let's see this using an example. I have two version of AND implementation below:

Version 1
def and(x:Boolean, y: Boolean):Boolean =  if(x) y else false

Version 2
def and(x:Boolean, y: => Boolean):Boolean =  if(x) y else false

Both of these version returns the same result when called with different boolean values for x and y. Though both of these versions are different, version 2 pass y using 'call by name' strategy, represented by '=>' symbol.
You must be wondering, so now what is the difference? Let's introduce a loop function

def loop: Boolean = loop

Analyzing the outputs of the two statements will give a better understanding of the these strategies.

and(false, loop)

Version 1 shall fall into an infinite loop since it's following a call by value strategy. While with version 2 the statement shall work fine.

Courtesy: Martin Ordersky for explaining it so beautifully, I am spreading his word here.