0

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))))
Óscar López
  • 232,561
  • 37
  • 312
  • 386
runners3431
  • 1,425
  • 1
  • 13
  • 30

1 Answers1

2

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • so anytime i want to run a lamda expression that is a formal parameter i need to do (lamdba-name paramater)? – runners3431 Jun 09 '14 at 18:20
  • @runners3431 yes, every time you need to _execute_ a `lambda` (it doesn't matter if it's a formal parameter or not) you have to pass the expected arguments. But it depends on the `lambda` expression, if it doesn't have parameters then it's ok to call it like this `(f)` - but if it has one, two, etc. parameters _and_ you need to invoke it, then the correct number of parameters must be provided. – Óscar López Jun 09 '14 at 18:29
  • @runners3431 There exist `lambda`s with variable number of arguments, and with optional arguments. I won't get into the details, but the key point is: a `lambda` is like any other procedure (except that it doesn't have a name), and you have to call it with the appropriate arguments – Óscar López Jun 09 '14 at 18:44
  • "a lambda is like any other procedure (except that it doesn't have a name" — Do any procedures have names? No. When you have a form like `(
    ...)`, you evaluate `
    `, and the value should be a procedure. The value of a variable can be a procedure (e.g., if you've done (define (foo …) …)` or `(let ((foo (lambda …`, and the value of `(lambda …)` is a procedure.
    – Joshua Taylor Jun 09 '14 at 20:52
  • @JoshuaTaylor What I meant to explain is that a lambda is an anonymous procedure – Óscar López Jun 09 '14 at 21:16