What's the point of lambda in scheme?

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))

Let is actually just shorthand for a Lambda expression. The following two expressions are equivalent:

(let ((alpha 7)) (* 5 alpha))

((lambda (alpha) (* 5 alpha)) 7)

Lambda follows the philosophy of the language that everything should look like a mathematical function. But in practice Let makes it easier to figure out what is happening if there are too many variables. Imagine 10 variables which have their values defined after the Lambda block, and you trying to match each of those with the variable name, with Let the values of variables are placed right next to their names, convenient for the programmer but conforming less to the Functional Programming philosophy.

Lambda can be used to return a function from a higher order function however let cannot do that. Eg:

(define (plus-list x)
  (cond ((number? x)
         (lambda (y) (+ (sum-n x) y)))
        ((list? x)
         (lambda (y) (+ (sum-list x) y)))
        (else (lambda (x) x))
        ))

> ((plus-list 3) 4)
10
> ((plus-list '(1 3 5)) 5)
14
> ((plus-list 'a) 5)
5

Lambda can also be used to pass a function to a function:

>(map (lambda (x) (+ 1 x)) '(-1 2 -3))
(0 3 -2)

Tags:

Lambda

Scheme

Let