runners3431
runners3431

Reputation: 1455

Explanation on passed procedure execution

In SICP lecture 2a, I'm confused on (average (f x) x). Can it not just be (average f x). Doesn't f mean the lambda of (/ x y) already? Why do I need (average (f x) x)? Could someone help me out with the substitution method for this?

(define (sqrt x)
    (fixed-point
        (average-damp (λ (y) (/ x y)))
        1))

(define average-damp
    (λ (f)
        (λ (x) (average (f x) x))))

Upvotes: 0

Views: 53

Answers (1)

Óscar López
Óscar López

Reputation: 236004

This snippet:

(average (f x) x)

Means a different thing than this:

(average (f) x)

For starters, f is a function that expects a single parameter, which in this case must be x, hence we say (f x) . If you write (f) you're trying to call f with no parameters, resulting in an error. Substituting in average-damp after calling it with a value for the f parameter we discover that it returns another lambda, which is:

(λ (x)
  (average ((λ (y) (/ x y)) x) x))

As you can see, in this expression ((λ (y) (/ x y)) x), x is passed as a parameter to (λ (y) (/ x y)) x) (which was f), and x binds to the y parameter. Don't get confused! because now we have:

(/ x x)

But the first x at this point is not a variable, it's the value that was captured in a closure when calling sqrt, whereas the second x is the parameter in the lambda that we just returned, and is still unbound until the point where it gets called, presumably in fixed-point.

Upvotes: 2

Related Questions