scheme varargs

function - How do I handle an unspecified number of parameters in Scheme? - Stack Overflow

34

In Scheme you can use the dot notation for declaring a procedure that receives a variable number of arguments (also known as varargs or variadic function):

(define (procedure . args)
  ...)

Inside procedureargs will be a list with the zero or more arguments passed; call it like this:

(procedure "a" "b" "c")

As pointed out by @Arafinwe, here's the equivalent notation for an anonymous procedure:

(lambda args ...)

Call it like this:

((lambda args ...) "a" "b" "c")

Remember that if you need to pass the parameters in a list of unknown size to a variadic function you can write it like this:

(apply procedure '("a" "b" "c"))
(apply (lambda args ...) '("a" "b" "c"))

UPDATE:

Regarding the code in the comments, this won't work as you intend:

(define (fp f)
  (lambda (.z)
    (f .z)))

I believe you meant this:

(define (fp f)
  (lambda z
    (apply f z)))

With a bit of syntactic sugar the above procedure can be further simplified to this:

(define ((fp f) . z)
  (apply f z))

But that's just a long way for simply writing:

(apply f z)

Is this what you need?

(apply string-append '("a" "b" "c"))

Because anyway that's equivalent to the following:

(string-append "a" "b" "c")

string-append already receives zero or more arguments (at least, that's the case in Racket)

Share

Edit

Follow

edited Sep 30, 2012 at 15:18

answered Sep 30, 2012 at 3:40

Óscar López

225k3434 gold badges301301 silver badges374374 bronze badges

Add a comment

7

In addition to Óscar López's answer, you can also make an anonymous function of variable arguments like so:

(lambda args ...)

Where again, inside the lambdaargs is a list of the arguments passed.

Share

Edit

Follow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值