如何定义可变参数函数 [英] How to define a variadic function

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

问题描述

我正在寻找类似于 Javascript 的 arguments 数组的东西:

I'm looking for something similar to Javascript's arguments array:

function parent(){
  child.apply(this.arguments);
}

我知道可变参数长度的点符号以及方案的 apply 函数.

I'm aware of the dot notation for variable argument lengths and also scheme's apply function.

这似乎不起作用,因为点被视为第一个参数:

This doesn't seem to work as the dot is taken to be the first argument:

(define (parent .) 
          (list .))

(parent 1 3 4 6 7)
Error: bad argument count - received 5 but expected 1: #<procedure (array arg-list)>

这可行,但并不理想.我想在没有额外语法的情况下调用函数来定义 args 列表:

This works but isn't ideal. I'd like to call the function without the extra syntax to define the args list:

(define (parent args-list)
     (apply list args-list))


(parent 1 3 4 6 7)
Error: bad argument count - received 5 but expected 1: #<procedure (array args-list)>

(parent `(1 3 4 6 7))
(1 3 4 6 7)

推荐答案

正确的语法是:

(define (parent . args-list)
    <do something with args-list>)

像这样使用它:

(parent 1 2 3 4 5)

在程序内部,所有参数都将绑定到一个名为args-list 的列表中.在上面的代码段中,args-list'(1 2 3 4 5) 作为它的值.这是在 Scheme 中可变参数函数如何工作的一个例子.

Inside the procedure, all the arguments will be bound to a list named args-list. In the above snippet, args-list will have '(1 2 3 4 5) as its value. This is an example of how variadic functions work in Scheme.

为了完整起见,同样的机制也可以用于匿名函数(注意args-list不是被括号包围):

For the sake of completeness, the same mechanism can be used for anonymous functions, too (notice that args-list is not surrounded by parenthesis):

((lambda args-list <do something with args-list>) 1 2 3 4 5)

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

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