How to make a Clojure function take a variable number of parameters?

rodrigoalvesvieira picture rodrigoalvesvieira · Feb 11, 2012 · Viewed 47.5k times · Source

I'm learning Clojure and I'm trying to define a function that take a variable number of parameters (a variadic function) and sum them up (yep, just like the + procedure). However, I don´t know how to implement such function

Everything I can do is:

(defn sum [n1, n2] (+ n1 n2))

Of course this function takes two parameteres and two parameters only. Please teach me how to make it accept (and process) an undefined number of parameters.

Answer

soulcheck picture soulcheck · Feb 11, 2012

In general, non-commutative case you can use apply:

(defn sum [& args] (apply + args))

Since addition is commutative, something like this should work too:

(defn sum [& args] (reduce + args))

& causes args to be bound to the remainder of the argument list (in this case the whole list, as there's nothing to the left of &).

Obviously defining sum like that doesn't make sense, since instead of:

(sum a b c d e ...)

you can just write:

(+ a b c d e ....)