Consider the following Python program. Python evaluates the left operand of + before the right one.
total = 20 def add_impure(x): global total total = total + x return total def add_pure(t, x): return t + x a = add_impure(4) + add_impure(4) b = add_pure(20, 4) + add_pure(20, 4)
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.
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 ________.
Counting argument evaluations under three strategies
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:
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.