开发者

apply first of a list of functions in Clojure

if i have a list of functions:

(def lst '(+ -))

and i wish to apply the first of that list (+) to a list of numbers, i would think its

开发者_JS百科

(apply (first lst) '(1 2 3 4))

but apparently U am wrong? Syntax mistake I assume. How do I do this?

PS:

=>(first lst)  
+

=>(apply (first lst) '(1 2 3 4))   
4

both return without error, they just return what i WOULD expect in the first case, and what i would NOT expect in the second.


Since your list is quoted:

(def lst '(+ -))
       ; ^- quote!

its members are two symbols, not functions. A symbol in Clojure can be used as a function, but then it acts very much like a keyword (i.e. looks itself up in its argument):

('foo {'foo 1})
; => 1

The correct solution is to use a list -- or, more idiomatically, a vector -- of functions:

(def lst (list + -)) ; ok
; or...
(def lst `(~+ ~-))   ; very unusual in Clojure
; or...
(def lst [+ -])      ; the idiomatic solution

Then your apply example will work.

By the way, notice that a function, when printed back by the REPL, doesn't look like the symbol which names it:

user=> +
#<core$_PLUS_ clojure.core$_PLUS_@10c10de0>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜