A list of functions
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.
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)
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.
精彩评论