Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass var args to an anonymous function in Clojure?

Tags:

clojure

Is it possible to do var args for an anonymous function in Clojure?

For example, how do I turn:

(#(reduce + (map * %1 %2 %3)) [1 2 3] [4 5 6] [7 8 9])

into something like,

(#(reduce + (map * [& args])) [1 2 3] [4 5 6] [7 8 9])
like image 670
jeemar Avatar asked Dec 15 '22 04:12

jeemar


2 Answers

This solves the problem:

 user> ((fn[& args] (reduce + (apply map * args))) [1 2 3] [4 5 6] [7 8 9])
       270

or

 user> (#(reduce + (apply map * %&)) [1 2 3] [4 5 6] [7 8 9])
       270
like image 184
guilespi Avatar answered Mar 15 '23 12:03

guilespi


Use the apply function

I'm not aware of a way to do this with the #(...) syntax, but here is your example using fn

((fn [& args] (reduce + (apply map * args))) [1 2 3] [4 5 6] [7 8 9])

You can use %& to get the rest argument in the #(...) form, resulting in

(#(reduce + (apply map * %&)) [1 2 3] [4 5 6] [7 8 9])
like image 26
cobbal Avatar answered Mar 15 '23 12:03

cobbal