4

I'm having some trouble figuring out how to use lambdas that are contained within lists in Scheme. For example, I have the following code:

(define abc '((lambda (x) (* x x))))

I would like to take the first lambda from the list and apply it to some numbers. Here is what I have so far:

(map (car abc) '(1 2 3))

However, I get the following error:

;The object (lambda (x) (* x x)) is not applicable.

But when I try the same thing directly using just the lambda, it works:

(map (lambda (x) (* x x)) '(1 2 3))
;Value 15: (1 4 9)

Can someone help me understand what I am doing wrong?

cascal
  • 2,943
  • 2
  • 17
  • 19
  • The issue as that you're treating `'((lambda ...))` as if it were the same as `(list (lambda ...))`, but they are radically different. [This question](https://stackoverflow.com/questions/34984552/what-is-the-difference-between-quote-and-list) and its answer do a good job at explaining why. – Alex Knauth Apr 28 '16 at 13:11
  • If you're confused about how `quote` works, then you will make many fewer mistakes if you just use `list` everywhere, and never use `quote` for lists at all, only for symbols. – Alex Knauth Apr 28 '16 at 13:16

1 Answers1

6

You should understand that

(lambda () 42)

and

'(lambda () 42)

are not the same thing. The first one when evaluated gives you back a callable object that when called returns 42, the second one when evaluated returns a list where the first element is the symbol lambda the second element is an empty list and the third element is the number 42.

Your code is defining abc as a list containing a list where the first element is the symbol lambda, not a list containing a callable function. For that you need to write

(define abc (list (lambda (x) (* x x))))

in other words a lambda form needs to be evaluated to give you a callable function.

6502
  • 112,025
  • 15
  • 165
  • 265
  • 1
    another notation, though less clear in this context, sometimes clearer if used the right way, is to use a quasiquote (back-tic `), which lets you quote a large data structure, but still evaluate parts of it with (unquote ,) – Anandamide Apr 23 '16 at 17:25
  • 1
    `(,(lambda (x) (* x x)) ,(lambda (x) x) ,(lambda (x) 5)) – Anandamide Apr 23 '16 at 17:27