如何使Clojure函数取可变数量的参数? [英] How to make a Clojure function take a variable number of parameters?

查看:83
本文介绍了如何使Clojure函数取可变数量的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Clojure,我试图定义一个函数,它接受可变数量的参数(一个可变参数函数)并将它们求和(yep,就像+过程)。但我不知道如何实现这样的功能。

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.

推荐答案

一般来说,非交换的情况下您可以使用套用

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

& c $ c> 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 ...)

/ p>

you can just write:

(+ a b c d e ....)

这篇关于如何使Clojure函数取可变数量的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆