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
- Default is Call By Value.
- 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.
- When the expressions only consists of pure functions (i.e., functions with no side effects)
- When both type of evaluations terminate.
- What are the advantages of both types of evaluation
- CBV has an advantage that it evaluates each argument only once.
- 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 ?
- Depends on the expression and values passed.
e.g for function evaluationdef test (x: Int, y:Int):Int = x * x
following are the expression evaluations
- test (2, 3) : both are same
- test (3+4, 8 ) : CBV is faster
- test (7, 2*4) : CBN is faster
- test(3+4, 2*4) : Both are same
- Depends on the expression and values passed.
Reference
https://www.coursera.org/learn/progfun1/home/welcome