Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 419
rodrigoalvesvieira Avatar asked Feb 11 '12 17:02

rodrigoalvesvieira


People also ask

How many parameters can a function take?

Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.

What is the syntax of variable number of parameters?

Syntax of VarargsA variable-length argument is specified by three periods or dots(…). This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a result, here, a is implicitly declared as an array of type int[].

How do you return a value in Clojure?

There isn't a return statement in Clojure. Even if you choose not to execute some code using a flow construct such as if or when , the function will always return something, in these cases nil .


1 Answers

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 ....) 
like image 157
soulcheck Avatar answered Sep 17 '22 03:09

soulcheck