Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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)

like image 993
unj2 Avatar asked Jun 03 '09 00:06

unj2


1 Answers

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)
like image 197
Jay Kominek Avatar answered Sep 25 '22 16:09

Jay Kominek