Lisp/Scheme/Racket:如何定义带有省略号的函数

dat*_*uoc 1 scheme function variadic-functions racket arity

我想在 Racket 中定义一个带有未定义参数数量的函数,所以我使用省略号,但它不起作用:

(define (f x ...) (printf x ...))
(f "~a ~a" "foo" "bar")
Run Code Online (Sandbox Code Playgroud)

错误:

Arity mismatch
Run Code Online (Sandbox Code Playgroud)

如何用省略号在 Racket 中定义一个函数?

Ale*_*uth 5

这有两半:

  1. 接受任意数量的输入
  2. 将任意数量的参数传递给另一个函数

要接受任意数量的输入,而不是...after x,请.在 before 中放置一个x。这声明x为“rest”参数,并且这些参数将被收集到一个列表中x

例子:

> (define (f . x) x)
> (f "~a ~a" "foo" "bar")
(list "~a ~a" "foo" "bar")
Run Code Online (Sandbox Code Playgroud)

要传递任意数量的参数,您可以使用该apply函数,该函数接受一个列表作为最后一个参数。

例子:

> (apply printf (list "~a ~a" "foo" "bar"))
foo bar
Run Code Online (Sandbox Code Playgroud)

把这些放在一起:

> (define (f . x) (apply printf x))
> (f "~a ~a" "foo" "bar")
foo bar
Run Code Online (Sandbox Code Playgroud)