I don't understand lambda in Scheme

Can someone please explain how lambda works in scheme? For example how it works here:

(define (prepend-every prefix sent)
  (every (lambda (wd) (word prefix wd)) sent))

Or here:

(define (first-last sent)
  (keep (lambda (wd) (equal? (first wd) (last wd))) sent))

> (first-last '(california ohio nebraska alabama alaska massachusetts))
- - Source


answered 5 year ago Óscar López #1

The special form lambda is an anonymous procedure, in the examples shown it's a shorthand to avoid defining a separate one-shot function. For example, the first snippet is equivalent to this:

(define (helper wd)
  (word prefix wd))

(define (prepend-every prefix sent)
  (every helper sent))

But why define a new procedure that's going to be used only once? that's why we use lambda in this case. Also, it's good to remember that a function definition written like this:

(define (f x)

… Is just a shorter syntax for this equivalent form:

(define f
  (lambda (x)

So you see, in the end all procedures in Scheme are lambdas under the hood. There are other special forms that can get transformed to lambdas, for example let, let*, etc. take a look at these posts for further clarification.

comments powered by Disqus