Search code examples
schemesicp

substitution model to evaluate (f f) in sicp


I am working on Exercise 1.34 of SICP

Exercise 1.34. Suppose we define the procedure

(define (f g)
  (g 2))

Then we have

(f square)
4

(f (lambda (z) (* z (+ z 1))))
6

What happens if we (perversely) ask the interpreter to evaluate the combination (f f)? Explain.

Refer to the solution:

Step 1:

(f f)

Step 2:

(f (lambda (g)
     (g 2)))

Step 3:

((lambda (g)
    (g 2))
 (lambda (g)
    (g 2)))

Step 4:

((lambda (g)
    (g 2))
 2)

Step 5:

(2 2)

I got the idea of the first 3 steps, as to step 4, How could the second f be evaluated as 2?

Other solution

The result is an error: using the substitution rule in (f f)

g = f : (g 2) -> (f 2)

Again using the substitution rule in (f 2)

g = 2 : (f 2)-> (2 2) -> error.

The actual error from DrRacket is:

The confusion remains, my mind slow to jump one step on "to be evaluated as 2".


Solution

  • It's a little easier to see what's going on if you define two equivalent procedures, and rename the variables to distinguish them.

    (define (f1 g1)
      (g1 2))
    (define (f2 g2)
      (g2 2))
    

    And now the question is about (f1 f2). Step 3 becomes:

    ((lambda (g1) ;; f1
        (g1 2))
     (lambda (g2) ;; f2
        (g2 2)))
    

    When f1 is called, g1 is replaced with the second procedure, and it calls (g1 2). So in step 4 with application model becomes:

    ((lambda (g2) ;; f2
        (g2 2))
     2)