I want to define a function in Racket with undefined number of arguments so I use ellipsis, but it doesn't work:
(define (f x ...) (printf x ...))
(f "~a ~a" "foo" "bar")
Error:
Arity mismatch
How to define a function in Racket with ellipsis?
There are two halves of this:
To accept an arbitrary number of inputs, instead of a ...
after x
, put a single .
before x
. This declares x
as the "rest" argument, and the arguments will be collected into a list for x
.
Example:
> (define (f . x) x)
> (f "~a ~a" "foo" "bar")
(list "~a ~a" "foo" "bar")
To pass an arbitrary number of arguments, you can use the apply
function, which accepts a list as the last argument.
Example:
> (apply printf (list "~a ~a" "foo" "bar"))
foo bar
Putting these together:
> (define (f . x) (apply printf x))
> (f "~a ~a" "foo" "bar")
foo bar