I am learning scheme. I know how to use both lambda and let expressions.
However I'm struggling to figure out what the point is of using lambda. Can't you do everything with let that you can with lambda?
It would be especially helpful to see an example of a situation where a lambda expression is a better choice than let.
One other thing - are there also situations where let is more useful than lambda? If so such an example would be nice as well.
Edit: I'm also interested in contrasting define and lambda, as they seem to perform similar tasks.
Thanks for the help everyone. I did some more looking into lambda/let/define after reading your answers, and now understand it a lot better.
I came accross an excellent example of cool lambda useage - returning anonymous functions from procedures. For example, the procedure operateTwice
below returns an anonymous function that is based on parameters passed in to the procedure:
(define operateTwice
(lambda (op1 op2)
(lambda (x y)
(op2 (op1 x y) y))))
((operateTwice * +) 2 3) ;equivalent to: (+ (* 2 3) 3), or in standard notation 2*3+3
Output:
9
A let
is a lambda
.
E.g.
(let ((x 1))
body)
can be translated into
((lambda (x) body) 1)
Furthermore, in Scheme all control and environment structures can be represented by lambda expressions and applications of lambdas.
So, lambda
is strictly more powerful than let
and forms the basis of many of the interesting constructs found in Scheme.
Concerning define
and lambda
, a top-level define
adds a binding to the top-level environment.
When you write
(define (f x)
body)
you are really saying
(define f (lambda (x) body))
Nested defines are translated into letrec
, which can be rewritten using lambdas as well.
So, again, a lot of Scheme constructs can be translated into something using lambda
, and therefore it is really worthwile that you understand lambda
well.