• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

functional programming (lisp / scheme) help

alpineranger

Senior member
For my own curiosity I'm going over some material I haven't touched in years. I'm a bit puzzled by the behavior of lambda functions. I can use them in basic ways, but my understanding is really lacking. For example, given the following expression:

( (lambda (y) (lambda (x) (+ x y)) 4) 5)
=> 4

I don't understand this result, as by my reckoning this should be equivalent to:

( (lambda (y) (+ 4 y)) 5)
=> 9

Basically, how does the binding of variables occur in this case. I've read the R5RS on lambda and it doesn't clarify things.

I know I can do something like:
( (let ((x 4)) (lambda (y) (+ x y)) )5 )
=> 9

but with the nested lambdas I'm baffled by the mechanics of binding. (Apologies for the potentially confusing use of parentheses)
 
Ok, let's look at this code:

(lambda (y) (lambda (x) (+ x y)) 4)

What is this? This isn't a function call. This is just defining a function. But what about that 4? It isn't the argument to a function call. That would be something like:

((lambda (x) (+ x 1)) 1)
=> 2

Note the extra set of parentheses used to make the function call.

Lacking those, you just have defined a function whose body is a list consisting of (lambda (x) (+ x y)) and 4. This function will just return the last element in the list, which is 4. Hence, when calling this function you'll just get 4. The extra set of parens around the (lambda (y) ...) calls the function with the argument 5, but that never gets added to anything since the function just returns 4 anyway.

The version that does what you're thinking of looks like this:

((lambda (y) ((lambda (x) (+ x y)) 4)) 5)

First, notice this part:

((lambda (x) (+ x y)) 4)

This calls the function (lambda (x) (+ x y)) with the argument 4, giving us (+ 4 y). Then we have

((lambda (y) (+ 4 y)) 5)

Which is of course (+ 4 5) = 9.
 
Ahh, I suspected it had something to do with the parentheses. I should probably use one of those environments that does automatic formatting. Yes, I was aware how lambda works, although I was unaware that the lambda only returns the last object in the lambda definition eg ((lambda(x) x 'y 'z) 5) ==> z
 
Back
Top