tags:

views:

148

answers:

2

Hi, I am learning Scheme. What is wrong with the code below?I want to write a program that takes the first function from the list and then applies that to a number?

    (define num  3)

    ;;I want to do something like this which returns 3
    ((λ (x) x)num)

    ;;but my functions are in a list so this should return3
    ((first '((λ (x) x) (λ (x) (* x x)))) num)

Im getting this error for the above code:
procedure application: expected procedure, given: (λ (x) x); arguments were: 3

What does it mean when I get these kinds of output?

When I dont apply anything, I get a nice output.

(first '((λ(x) x)(λ(x) (*x x))))

returns (λ (x) x)

+6  A: 

You're quoting, with ' the lambda, so it isn't being evaluated.

If you just feed in (λ (x) x) at the prompt, DrScheme shows you #<procedure>, which means it has actually evaluated the lambda, and given you back a closure. By quoting it, you're giving Scheme just a list of symbols.

If you want to put your functions in a list, you can do:

((first (list (lambda (x) x) (lambda (x) (* x x)))) num)

The quote allows you to produce a list, yes, but one whose contents aren't evaluated. The list function produces a list from all of its arguments, after they've been evaluated.

You could also quasiquote the list, if you like:

((first `(,(lambda (x) x) ,(lambda (x) (* x x)))) num)
Jay Kominek
Thank you .
kunjaan
A: 

What is the difference between these expressions?

> (procedure? (lambda (n) n))
#t
> (procedure? (quote (lambda (n) n)))
#f
> (procedure? '(lambda (n) n))
#f

Jay answered it for you but I can't upvote him yet.

grettke