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
Lambda is the name of a special form that generates procedures. It takes some information about the function you want to create as arguments and it returns the procedure. It'll be easier to explain the details after you see an example.
Lambda runs your code on high availability compute infrastructure and performs all the administration of your compute resources. This includes server and operating system maintenance, capacity provisioning and automatic scaling, code and security patch deployment, and code monitoring and logging.
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.
You use lambda
if you want to create a function to use it as an argument to another function (like for example map
), but you don't actually want to name the function.
For example, if you want to add 42 to every number in a list, you can do:
(define (add42 x) (+ x 42)) (map add42 (list 1 2 3 4))
But if you don't want to give a name to a function that you only use this once, you could just do:
(map (lambda (x) (+ x 42)) (list 1 2 3 4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With