Search code examples
lambdaschemelisphigher-order-functionsmit-scheme

How to use lambdas from a list in Scheme


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?


Solution

  • 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.