Functional languages differ in when they evaluate the arguments of a call. Under call-by-value (used by ML and Scheme), every argument is evaluated exactly once before the function body runs. Under call-by-name, the unevaluated argument expression is substituted into the body and evaluated again each time the body uses that parameter. Under call-by-need (the lazy evaluation of Haskell), the argument is evaluated only the first time the body uses it, and the stored value is reused after that.
Consider these pure functions:
twice x = x + x first x y = x pick b x = if b then x + x else 0
Let e stand for the argument expression (10 * 7). For each call, enter the number of times the multiplication 10 * 7 is performed. The literal arguments 4 and False need no work, and two separately written copies of e are separate expressions that do not share a result.
Unlock full course notes by signing up
Evaluating a recursive definition by substitution
A pure Haskell function is defined recursively as follows, where function application binds more tightly than multiplication, and multiplication more tightly than addition.
Evaluate f 4 by substitution. Give the result as an integer.
Tracing an accumulator recursion
The pure Haskell function below sums the integers from 1 to n by passing a running total as an argument instead of updating a loop variable.
The expression sumTo 0 5 is evaluated. Complete the table with the values of acc and n in each successive call, as integers. Call 1 is given.
Immutable lists after building new ones
In Haskell, list values are immutable. The operator : builds a new list by placing one element in front of an existing list, tail returns a list without its first element, and ++ joins two lists into a new list. A program contains these three definitions:
After all three definitions have been evaluated, xs contains ________ elements and ys contains ________ elements. The list zs contains ________ elements. The sum of the elements of xs is ________, and the sum of the elements of zs is ________.
How a side effect breaks substitution
Consider the following Python program. Python evaluates the left operand of + before the right one.
Find the value of a, the value of b, and the final value of total after both assignment lines have run. Give each as an integer.