Apply function list to parameter, clojure

(def ops '(+ - * /)) (map #(% 2 5) ops) 

gives

 (5 5 5 5) 

That doesn't make sense to me. Why does this return a list of 5 instead of the results of function calls?

+5
source share
3 answers

The problem is that '(+ - * /) is a list of characters, not a list of functions. Characters implement AFn and, if there are two arguments, the function tries to find the character in the first argument ( 2 here) and returns the second argument ( 5 here) if the search fails.

+7
source

This works: (map #(% 2 5) [+ - * /])

This is not: (map #(% 2 5) '[+ - * /])

And it does not: (map #(% 2 5) '(+ - * /))

The reason is that when you do '(+ - * /) , you get a list of +, - * and / characters, and not the functions to which they refer - the quote also refers to the list values.

Using a vector avoids this problem.

If you absolutely need a list, do (map #(% 2 5) (list + - * /)) .

+11
source

Clojure has a function that does exactly what you want: juxt : http://clojuredocs.org/clojure.core/juxt

So your example will be

 (def funcs (juxt + - * /)) (funcs 2 5) 

If someone comes up with a good explanation why the map approach does not work, I would also like to hear that.

+4
source

All Articles