Q1)What is Call-by-Value and Call-by-name in Scala?
Ans:
Define One Function
def sumOfSquares(x: Double, y: Double) = square(x) + square(y)
Call-by-value
Call-by-value has the advantage that it avoids repeated evaluation of arguments.
Call-by-value is usually more efficient than call-by-name.
example:
sumOfSquares(5, 3+3)
→ sumOfSquares(5, 6)
→ square(5) + square(6)
→ 5 * 5 + square(6)
→ 25 + square(6)
→ 25 + 6 * 6
→ 25 + 36
→ 61
Call-by-name
Call-by-name has the advantage that it avoids evaluation of arguments when the
parameter is not used at all by the function.
example:
sumOfSquares(5, 3+3)
→ square(5) + square(3+3)
→ 5 * 5 + square(3+3)
→ 25 + square(3+3)
→ 25 + (3+3) * (3+3)
→ 25 + 6 * (3+3)
→ 25 + 6 * 6
→ 25 + 36
→ 61
Note:
Scala uses call-by-value by default, but it switches to call-by-name evaluation if the
parameter type is preceded by =>
No comments:
Post a Comment