jeemar
jeemar

Reputation: 548

How do I pass var args to an anonymous function in 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])

Upvotes: 5

Views: 2250

Answers (2)

cobbal
cobbal

Reputation: 70703

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])

Upvotes: 2

guilespi
guilespi

Reputation: 4702

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

Upvotes: 10

Related Questions