我正在学习Clojure,并且我正在尝试定义一个函数,该函数接受可变数量的参数(一个可变函数)并对它们求和(是的,就像+过程一样)。然而,我不知道如何实现这样的功能
我能做的就是:
(defn sum [n1, n2] (+ n1 n2))
当然,这个函数只接受两个参数和两个参数。请教我如何让它接受(和处理)未定义数量的参数。
发布于 2012-02-12 02:09:23
通常,在非交换情况下,可以使用apply
(defn sum [& args] (apply + args))
因为加法是可交换的,所以下面这样的代码也应该有效:
(defn sum [& args] (reduce + args))
&
导致args
绑定到参数列表的其余部分(在本例中是整个列表,因为&
左边没有任何内容)。
显然,这样定义sum是没有意义的,因为不是:
(sum a b c d e ...)
你可以这样写:
(+ a b c d e ....)
发布于 2012-02-20 11:09:59
Yehoanathan提到了a重载,但没有提供直接的例子。以下是他所说的:
(defn special-sum
([] (+ 10 10))
([x] (+ 10 x))
([x y] (+ x y)))
(special-sum)
=> 20
(special-sum 50)
=> 60
(special-sum 50 25)
=> 75
发布于 2014-10-26 07:47:47
(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))
)
https://stackoverflow.com/questions/9242440
复制相似问题