62 3 Functional Programming Languages
Call-By-Need or Lazy Evaluation:
A parameter is only evaluated if its value is needed, and then just once. The first
use, thus, forces us to evaluate the parameter. All subsequent uses may access
the value, which has already been memorized. This strategy is used for example
by the programming language H
ASKELL.
Call-by-need can be seen as an optimization of call-by-name, which tries to combine
the good termination behavior of call-by-name with the efficiency of call-by-value.
Postponing the evaluation of subexpressions is, however, not for free: it requires
additional management overhead. For the programming language F
UL, weleave the
strategy for parameter passing open and present translation schemes both for call-
by-value (CBV) and call-by-need (CBN).
Forthediscussionofparameterpassing,wehavesofarleftopenwhetherstaticor
dynamic scoping is used, even though these two considerations are not independent
of each other. With static scoping, the use of a name always relates to the textu-
ally innermost enclosing construct that defines the name. With dynamic scoping,the
dynamically last binding for a name defines the value of the name.
Example 3.2.3 Consider the following program:
let x
= 2 in
let f
= fun y → x + y in
let h
= fun gx→ g 2 in
hf1
With static scoping, the free variable x in the body of f refers to the definition x
= 2.
Therefore, the value of hf1 is 4. With dynamic scoping, x is bound to 1, before the
value of x is accessed in the body of f . Consequently, the value is 3.
Evaluation with static scoping leads always to the same result, as expressions have
a fixed binding for their free variables. This property is also called referential trans-
parency. As with all modern functional programming languages, we choose static
scoping for F
UL.
This choice affects the implementation of function application. Consider again
the application hf1 with call-by-need parameter passing. Static scoping enforces
that the free variable x in the definition fun y
→ x + y of f obtains its value accord-
ing to the textually enclosing let-construct. In this particular example, x is therefore
bound to the value 2.
Such a binding is also called an environment. In order to ensure that for each
free variable in the expression e
i
for a formal parameter x
i
, always the correct envi-
ronment is available at each use of e
i
, the appropriate environment must be passed
along with the expression e
i
. Note that this environment is only known at run-time.
The resulting pair of an expression and an environment for all free variables in the
expression is called a closure. Sometimes, environments are also required for pro-
grams with call-by-value parameter passing. This is the case when, as in Example
3.2.3, functions may contain free variables.