-2

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))
'(OHIO ALABAMA ALASKA)
YetAnotherBot
  • 1,937
  • 2
  • 25
  • 32

1 Answers1

4

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

… Is just a shorter syntax for this equivalent form:

(define f
  (lambda (x)
    <body>))

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.

Community
  • 1
  • 1
Óscar López
  • 232,561
  • 37
  • 312
  • 386