Abstract
When we call a function with a few parameters, we are used to the fact that each parameter is evaluated before the function is called. This is known as eager evaluation. We can also say that such type of function is strict.
Vita, si uti scias, longa est. alium insatiabilis tenet auaritia; alium in superuacuis laboribus operosa sedulitas. Seneca, De brevitate vitae II.I.
Access this chapter
Tax calculation will be finalised at checkout
Purchases are for personal use only
Notes
- 1.
This is one of the reasons why we stated in Sect. 2.6.1 that it is more convenient to associate the types to the function and not to the arguments.
- 2.
Personal comment. From a user perspective, I would have preferred pass by need in Scala. If you program in a functional way with no side effects it is unnecessary to reevaluate an expression everytime you find it. Of course, in case of side effects pass by need and pass by name can lead to different results.
- 3.
In the example we use the following definition for addPair:
val addPair: (((Int,Int))=>Int) = (a) => a._1 + a._2
Note that here, a is a pair , and a._1 is an expression that returns the first element of the pair, and a._2 is an expression that returns the second one. An alternative way is to define
val addPair: (((Int,Int))=>Int) = (a) =>
a match case (a1,a2) => a1+a2
In this case we decompose the object a by means of match in the two components and add them. Unfortunately Scala does not permit the following to directly destructure the pair in the two components.
val addPair: (((Int,Int))=>Int) = ((a,b)) => a+b
For comparison, Standard ML permits this type of structure in the pattern matching. Observe the following valid code in Standard ML:
val addPair = fn (a,b) => a+b;
addPair (2,3);
val addPairOfPair = fn ((a,b),(c,d)) => a+b+c+d;
addPairOfPair ((4,3),(3,1));
Author information
Authors and Affiliations
Corresponding author
Rights and permissions
Copyright information
© 2016 Springer International Publishing AG
About this chapter
Cite this chapter
Torra, V. (2016). Lazy and Eager Evaluation. In: Scala: From a Functional Programming Perspective. Lecture Notes in Computer Science(), vol 9980. Springer, Cham. https://doi.org/10.1007/978-3-319-46481-7_3
Download citation
DOI: https://doi.org/10.1007/978-3-319-46481-7_3
Published:
Publisher Name: Springer, Cham
Print ISBN: 978-3-319-46480-0
Online ISBN: 978-3-319-46481-7
eBook Packages: Computer ScienceComputer Science (R0)