functionschemeracketvariadic-functionsarity

Lisp/Scheme/Racket: How to define a function with ellipsis


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?


Solution

  • There are two halves of this:

    1. accepting an arbitrary number of inputs
    2. passing an arbitrary number of arguments to another function

    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