如何使 Clojure 函数采用可变数量的参数? [英] How to make a Clojure function take a variable number of parameters?
问题描述
我正在学习 Clojure,我正在尝试定义一个函数,该函数接受可变数量的参数(一个 variadic 函数)并将它们相加(是的,就像 + 过程一样).但是,我不知道如何实现这样的功能
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
我能做的就是:
(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.
推荐答案
一般情况下,非交换情况可以使用 apply:
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))
&
导致 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 &
).
显然这样定义 sum 没有意义,因为不是:
Obviously defining sum like that doesn't make sense, since instead of:
(sum a b c d e ...)
你可以写:
(+ a b c d e ....)
这篇关于如何使 Clojure 函数采用可变数量的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!