SICP Exercise 3.8
Question
When we defined the evaluation model in 1.1.3, we said that the first step in
evaluating an expression is to evaluate its sub-expressions. But we never
specified the order in which the sub-expressions should be evaluated (e.g., left
to right or right to left). When we introduce assignment, the order in which the
arguments to a procedure are evaluated can make a difference to the
result. Define a simple procedure f
such that evaluating
(+ (f 0) (f 1))
will return 0
if the arguments to +
are evaluated from left to right but
will return 1
if the arguments are evaluated from right to left.
Answer
The following works:
(define f
(let ((x 2))
(λ (n)
(set! x (- x 1))
(* x n))))
If (+ (f 0) (f 1))
is evaluated from left to right, we get \((1\times
0)+(0\times 1)=0\). If it is evaluated from right to left, we get \((1\times
1)+(0\times 0)=1\).
Unfortunately, we can’t really test this without changing the Scheme interpreter
itself. For what it’s worth, debugging through the program flow reveals that
Scheme evaluates the two procedures from left to right, yielding a result of 0
.