2

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.

1
  • Ammar: By hand, expand-out and show what the code would do that you wrote. Next, do the same thing with your new code. You should see the difference.
    – grettke
    Commented Dec 26, 2009 at 0:20

2 Answers 2

10

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)
2
  • 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). Commented Dec 25, 2009 at 1:25
  • 2
    Thanks for pointing the (list #'+ #'- #'* #'/), it lead me to what I wanted. Commented Dec 25, 2009 at 13:04
2

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.