如何使一个 Clojure 函数采取一个可变数目的参数?

我正在学习 Clojure,我正在尝试定义一个函数,它接受一个可变数目的参数(一个 变数函数) ,然后对它们进行求和(是的,就像 + 过程一样)。但是,我不知道如何实现这样的功能

我能做的就是:

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

当然,这个函数只接受两个参数和两个参数。请教我如何使它接受(和处理)未定义数量的参数。

52331 次浏览

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

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

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

 (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))
)
(defn sum [& args]
(print "sum of" args ":" (apply + args)))

This takes any number of arguments and add them up.