如何在Scheme中处理未指定数量的参数? [英] How do I handle an unspecified number of parameters in Scheme?

查看:155
本文介绍了如何在Scheme中处理未指定数量的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如((fn-stringappend string-append) "a" "b" "c"),我知道如何处理此(f x y z).但是,如果参数数量未知,该怎么办?有什么办法可以解决这种问题?

For example ((fn-stringappend string-append) "a" "b" "c") I know how to handle this (f x y z). But what if there's an unknown number of parameters? Is there any way to handle this kind of problem?

推荐答案

在Scheme中,您可以使用点号来声明一个接收可变数量参数的过程(也称为 varargs 变数函数):

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

procedure内,args将是一个列表,其中传递了零个或多个参数.这样称呼它:

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

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

@Arafinwe指出,这是匿名过程的等效表示法:

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

(lambda args ...)

这样称呼:

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

更新:

关于注释中的代码,这将无法按您预期的方式工作:

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

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

我相信你的意思是

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

这是您需要的吗?

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

因为无论如何,它等同于以下内容:

Because anyway that's equivalent to the following:

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

string-append 已经已经收到零个或多个参数(至少在Racket中就是这种情况)

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

这篇关于如何在Scheme中处理未指定数量的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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