Call by Name vs Call by Value in Scala

This information is based on the coursera course “Functional Programming Principles in Scala” by Martin Odersky.

In Scala expressions* are evaluated by the Scala interpreter following the substitution model. What does this mean? What are expressions, and what means they are evaluated? An expression could be something as simple as “4+3”. Its the combination of some entities. Entities can be primitive or more complex structures. A primitive would be an Integer, a more complex structure could be a function, which is a named expression, so that we can use the name to reference the expression, e.g. “square(3)+square(4)”. “Evaluating an expression” means to reduce it to its value. For example, evaluating the expression 4+3 means that it is reduced to 7. If the expression is (4+3) * pi, you could first reduce 4+3 to 7 and then substitute pi by its value and then finally compute the result. You could also firstly replace pi by its value and then compute 4+3=7. So, the evaluating an expression can be done in various ways. Scala uses the way which is described by the substitution model. Or redundantly spoken: The substitution model is is a model that describes how to do the reduction of an expression to its value. It is formalized in $\lambda$-caluculus. Here is how a function application is evaluated by the Scala interpreter using the substitution model:

  1. evaluate all function arguments from left to right
  2. replace the function application by its right hand side and at the same time 
  3. replace the formal parameters of the function by the arguments

Example: You have 2 functions:

def square(x: Double) x*x

def sumOfSquares(x: Double, y: Double) square(x) + square(y)

The below table with the column header “Call by Value” shows how you evaluate the function application sumOfSquares(3, 2+2) using the substitution model. 

Now, rule number one above says “evaluate all function arguments from left to right”, so sumOfSquares(3,2+2) in the first step reduces to sumOfSquares(3,4) and then by applying rule 2 (replace the function application by it right hand side and plug in the arguments) we obtain square(3) +square(4). We could also delay the step of the argument evaluation and instead call the function applications right hand side with the unevaluated arguments (if any) and delay the evaluation for later. This strategy is called “Call by Name” and an example is given in the column called “Call by Name” in below table.

 

 

 

 

Was this helpful?

1 / 0

© 2025 yet another webpage
Cookie Consent with Real Cookie Banner