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.
Consider a function

def sumSquares(x: Int, y: Int): Int = square(x) + square(y)
def square(x: Int): Int = x*x

Now suppose we have an expression – sumSquares(3, 2+2).
A call by value evaluation of above expression will be

= sumSquares(3, 2+2) 
= sumSquares(3,4)
= square(3) + square(4)
= 3*3 + square(4)
= 9 + 4*4
= 9 + 16
= 25

Call by Name

Call by Name avoids evaluation of parameters if it is not used in the function body.

A Call By Name evaluation of same expression – sumSquares(3, 2+2), will be

= sumSquares(3, 2+2)
= square(3) + square (2+2)
= 3*3 + square(2+2)
= 9 + square(2+2)
= 9 + (2+2) * (2+2)
= 9 + 4 * (2+2)
= 9 + 4*4
= 9 + 16
= 25

 

  • What is the default evaluation strategy in Scala. How can you change it to call by name
    1. Default is Call By Value.
    2. Parameters can be passed as call by name using => e.g
      In below example, ‘x‘ argument is evaluated using call by value, but ‘y‘ argument is evaluated using call by name.

      def eval (x: Int , y: => Int): Int

 

  • When would both CBV and CBN evaluate to same results.
    1. When the expressions only consists of pure functions (i.e., functions with no side effects)
    2. When both type of evaluations terminate.

 

  •  What are the advantages of both types of evaluation
    1. CBV has an advantage that it evaluates each argument only once.
    2. CBN has an advantage that a function argument is not evaluated if corresponding parameter is not used in function evaluation

 

  • Which substitution model results in faster evaluation – CBV or CBN ?
    1. Depends on the expression and values passed.
      e.g for function evaluation

      def test (x: Int, y:Int):Int = x * x

      following are the expression evaluations

      1. test (2, 3) :  both are same
      2. test (3+4, 8 ) : CBV is faster
      3. test (7, 2*4) : CBN is faster
      4. test(3+4, 2*4) : Both are same

 

Reference

https://www.coursera.org/learn/progfun1/home/welcome