unj2
unj2

Reputation: 53481

How do I Apply an Anonymous Function from a List in Scheme?

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)

Upvotes: 6

Views: 1124

Answers (3)

rptb1
rptb1

Reputation: 480

(lambda (x) x) isn't a procedure. It's a form that evaluates to a procedure. People are a bit loose with terminology and often call the lambda form a procedure as a kind of shorthand. “Ceci n'est pas une pipe.”

Upvotes: 2

grettke
grettke

Reputation: 1417

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.

Upvotes: 2

Jay Kominek
Jay Kominek

Reputation: 8783

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)

Upvotes: 11

Related Questions