functional programming (lisp / scheme) help

alpineranger

Senior member
Feb 3, 2001
701
0
76
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)
 

esun

Platinum Member
Nov 12, 2001
2,214
0
0
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.
 

alpineranger

Senior member
Feb 3, 2001
701
0
76
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