Question

In scheme, how can I access a certain function inside of a list and pass a variable to that function?

(define f 
        '((lambda (n) (+ n 2)) 
          (lambda (n) (* n 2)) 
          (lambda (n) (* n n))))

I have defined this list f which has in it 3 different functions and I want to know what I can type into scheme to be able to say pass 3 to the second function in the list?

I thought that something like ((cadr f) 3) would work but I can't seem to figure it out, any help would be appreciated I'm really new to Scheme.

Was it helpful?

Solution

What you have here isn't a list of function but a list of list of symbols. Containing also some symbols... Since you quoted everything, then everything is quoted and only numbers and lists, strings are self-quoted. If you want to keep objects inside a list, you have two choices here:

Create a list instead of quoting it.

(define f 
        (list (lambda (n) (+ n 2)) 
              (lambda (n) (* n 2)) 
              (lambda (n) (* n n))))

Pseudo-quote it and unquote each function declaration

(define f 
        `(,(lambda (n) (+ n 2)) 
          ,(lambda (n) (* n 2)) 
          ,(lambda (n) (* n n))))

To be honest, the explicit list seems a bit nicer than the pseudo-quote version.

What your quoted version gives you is this:

(define f 
        (list (list 'lambda (list 'n) (list '+ 'n 2)) 
              (list 'lambda (list 'n) (list '* 'n 2)) 
              (list 'lambda (list 'n) (list '* 'n 'n))))

Quote isn't a shorthand for makings lists. It's a shorthand to not evaluate anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top