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

FunctionClojureLispProcedure

Function Problem Overview


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.

Function Solutions


Solution 1 - Function

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

Solution 2 - Function

Yehoanathan mentions arity overloading but does not provide a direct example. Here's what he's talking about:

(defn special-sum
  ([] (+ 10 10))
  ([x] (+ 10 x))
  ([x y] (+ x y)))

(special-sum) => 20

(special-sum 50) => 60

(special-sum 50 25) => 75

Solution 3 - Function

 (defn my-sum
  ([]  0)                         ; no parameter
  ([x] x)                         ; one parameter
  ([x y] (+ x y))                 ; two parameters
  ([x y & more]                   ; more than two parameters
    
 
    (reduce + (my-sum x y) more))
  )

Solution 4 - Function

> defn is a macro that makes defining functions a little simpler. > Clojure supports arity overloading in a single function object, > self-reference, and variable-arity functions using &

From http://clojure.org/functional_programming

Solution 5 - Function

(defn sum [& args]
  (print "sum of" args ":" (apply + args)))

This takes any number of arguments and add them up.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrodrigoalvesvieiraView Question on Stackoverflow
Solution 1 - FunctionsoulcheckView Answer on Stackoverflow
Solution 2 - FunctionDevin WaltersView Answer on Stackoverflow
Solution 3 - FunctionhariszamanView Answer on Stackoverflow
Solution 4 - FunctionviebelView Answer on Stackoverflow
Solution 5 - Functionuser4813927View Answer on Stackoverflow