如何让 Clojure 函数接受可变数量的参数?
我正在学习 Clojure,我正在尝试定义一个函数,该函数采用可变数量的参数(可变函数)并对它们进行求和(是的,就像 + 过程一样)。但是,我不知道如何实现这样的函数
我能做的就是:
(defn sum [n1, n2] (+ n1 n2))
当然这个函数需要两个参数并且只需要两个参数。请教我如何让它接受(并处理)未定义数量的参数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一般来说,非交换的情况你可以使用 apply:
由于加法是可交换的,所以像这样的东西也应该起作用:
&
导致args
绑定到参数列表的其余部分(在本例中是整个列表,因为&
左侧没有任何内容)代码>)。显然这样定义 sum 是没有意义的,因为
你可以写:
In general, non-commutative case you can use apply:
Since addition is commutative, something like this should work too:
&
causesargs
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:
you can just write:
Yehoanathan 提到了参数重载,但没有提供直接的例子。这就是他所说的:
(special-sum)
=>;20
(特殊总和 50)
=>60
(特殊总和 50 25)
=>75
Yehoanathan mentions arity overloading but does not provide a direct example. Here's what he's talking about:
(special-sum)
=>20
(special-sum 50)
=>60
(special-sum 50 25)
=>75
来自 http://clojure.org/function_programming
From http://clojure.org/functional_programming
这需要任意数量的参数并将它们相加。
This takes any number of arguments and add them up.