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

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

问题描述

我正在寻找类似于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天全站免登陆