Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

apply first of a list of functions in Clojure

Tags:

syntax

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

(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.

like image 463
trh178 Avatar asked Jul 22 '10 16:07

trh178


1 Answers

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>
like image 156
Michał Marczyk Avatar answered Nov 12 '22 22:11

Michał Marczyk