Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SICP exercise 3.8 - Why the procedure works? (I think it's about the environment)

Tags:

lisp

scheme

sicp

The exercise 3.8 in the SICP is described as blow:

When we defined the evaluation model in section 1.1.3, we said that the first step in evaluating an expression is to evaluate its subexpressions. But we never specified the order in which the subexpressions 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.

And I wrote the procedure f so that if I call (f x) first, it will always return x whenever I call f again. But I do not know exactly why it works. The procedure I wrote is:

(define f
  (let ((s -1))
    (lambda (x)
      (if (= s -1)
          (begin (set! s x)
                 s)
           s))))
like image 676
Bin Wang Avatar asked Oct 22 '25 19:10

Bin Wang


1 Answers

Think of s as a special variable tied just to your procedure, keeping its value between its invocations. Since you're going through SICP it should be clear that it's part of the environment that the procedure attached to f lives in.

First time it's called with some X, it sets s to x and returns it. Next time, since s is no longer -1, it will just always return s, which is the value of x saved in the first call.

> (f 42)  ; s is -1, so 42 is saved into it and returned
42
> (f 10)  ; is is 42, so the 'else' branch of the 'if' is taken
          ; and s is returned without looking at x
42
> (f 20)
42
> 
like image 76
Eli Bendersky Avatar answered Oct 25 '25 13:10

Eli Bendersky