tags:

views:

60

answers:

1

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

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

but apparently i 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.

+8  A: 

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>
Michał Marczyk
ahhhhhh. that makes so much sense now. just had to hear it from somebody that knew what they were doing. thanks a lot.
Toddeman