views:

179

answers:

2

Hello, Is there a way to make a list that holds functions? What I'm trying to do is, make a list of some arithmetic operators (+ - * /) so I can easily manipulate their order and apply them to a list of numbers.

So, if I have that list, I'd use it like this:

(apply (map (lambda (x)
              x)
            '(+ - * /))
       '(1 2 3 4))

I'm a novice programmer, so if there's a better way to do such operation, your advice is much appreciated.

+10  A: 

Lists are made with the function LIST.

(list 1 2 3)

(list + - * /)

Applying a list of symbols makes no sense:

(apply (map (lambda (x) x) '(+ - * /)) '(1 2 3 4))

Would be (applying a list of functions still makes no sense):

(apply (map (lambda (x) x) (list + - * /)) '(1 2 3 4))

Simplified (still wrong):

(apply (list + - * /) '(1 2 3 4))

But, maybe you wanted this:

(map (lambda (f)
       (apply f '(1 2 3 4)))
     (list + - * /))

In Common Lisp:

(mapcar #'(lambda (f)
            (apply f '(1 2 3 4)))
        (list #'+ #'- #'* #'/))

Returns:

(10 -8 24 1/24)
Rainer Joswig
What I want is to return the result from applying these functions in that order to the list, (+ 1 (- 2 (* 3 4))), (ignore the extra element in the function list).
Ammar Abdulaziz
well, apply only takes a single function, not a list of functions.Try again...
Rainer Joswig
Thanks for pointing the (list #'+ #'- #'* #'/), it lead me to what I wanted.
Ammar Abdulaziz
+2  A: 

I'm surprised no one has mentioned quasiquotation. :-) In Scheme, you could say:

`(,+ ,- ,* ,/)

or in Common Lisp:

`(,#'+ ,#'- ,#'* ,#'/)

In some cases, especially involving complex lists, quasiquotation makes the code much simpler to read than the corresponding list version.

Chris Jester-Young