Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Higher-order Functions

apply, Variadic Functions and Optional Arguments

Write functions that accept any number of arguments in Racket and Scheme: rest parameters, apply, optional and keyword arguments, and a small statistics toolkit.

You already use functions like +, max and string-append that accept any number of arguments. In this lesson you learn how to write such variadic functions yourself, how apply calls a function with a list of arguments, and how Racket adds optional and keyword arguments on top. These three ideas fit together: apply is the inverse of a rest parameter.

Rest parameters and apply run on the stand-in interpreter. Optional and keyword arguments are real-Racket-only, so they are shown read-only.

Rest parameters

A dot before the last parameter collects all extra arguments into a list:

RACKET
(define (my-list . items) items)
(my-list 1 2 3)       ; '(1 2 3)
(my-list)             ; '()

You can mix fixed parameters and a rest parameter. The fixed ones come first:

RACKET
(define (greet greeting . names)
  (map (lambda (n) (string-append greeting ", " n "!")) names))
(greet "Hello" "Ada" "Alan")   ; '("Hello, Ada!" "Hello, Alan!")

If a lambda has only a rest parameter, write it without parentheses: (lambda args ...) takes any number of arguments as the list args.

Rest parameters

A variadic sum and average

Because the extra arguments arrive as a list, you can use everything you learned about lists:

RACKET
(define (average first . rest)
  (/ (apply + first rest) (+ 1 (length rest))))
(average 2 4 6)    ; 4

Taking one required argument before the rest list makes (average) an arity error, which is correct: the average of nothing is undefined.

apply

(apply f arg ... lst) calls f with the individual args followed by the elements of the final list. It converts "a function and a list" into "a call":

RACKET
(apply + '(1 2 3 4))        ; 10     same as (+ 1 2 3 4)
(apply max '(3 9 2))        ; 9
(apply + 1 2 '(3 4))        ; 10     leading arguments plus a list
(apply string-append '("a" "b" "c"))   ; "abc"

Without apply, (+ '(1 2 3)) would try to add a list and fail. apply unpacks it. Use it whenever your data is already in a list but the function wants separate arguments.

apply

The fifth line is a famous idiom: (apply map list matrix) transposes a list of rows, because map with several lists walks them in parallel. The last line shows the error when you forget apply.

Passing arguments through

Rest parameters and apply together let a wrapper pass its arguments to another function untouched. This is how wrappers such as logging or timing helpers work:

RACKET
(define (logged f)
  (lambda args
    (displayln (list 'calling args))
    (apply f args)))

(define logged-add (logged +))
(logged-add 1 2 3)
A logging wrapper

logged works for functions of any arity because it never needs to know how many arguments there are.

Optional arguments (real Racket)

Racket lets a parameter have a default value, written in square brackets:

RACKET
(define (greet name [greeting "Hello"])
  (string-append greeting ", " name "!"))

(greet "Ada")            ; "Hello, Ada!"
(greet "Ada" "Welcome")  ; "Welcome, Ada!"

Optional parameters come after required ones, and the default expression is evaluated each time it is needed. If a default has to depend on an earlier argument, that is allowed too: (define (box w [h w]) ...).

Keyword arguments (real Racket)

For functions with many options, keywords make calls self-describing and order-independent:

RACKET
(define (make-circle #:radius r #:color [color "black"])
  (list 'circle r color))

(make-circle #:radius 5)
(make-circle #:color "red" #:radius 5)

A keyword argument starts with #:. The one with a bracketed default is optional. Keyword arguments and keyword-apply are used heavily in the Racket libraries; for example (sort lst < #:key car) sorts by the first element of each item and (string-join lst ", ")'s relatives accept #:before-first.

Variadic functions from first principles

Here is a small statistics toolkit built from the pieces above:

A statistics toolkit

Notice (apply total xs): summary itself receives a list xs, and apply turns that list back into separate arguments for the helpers.

Where to go next

You have now seen the core of functional programming in Racket: lists, recursion, closures, map/filter/fold, composition, and variadic functions. The next chapters build on this foundation with deeper control (tail calls and continuations), then macros, which let you add new syntax.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (define (f a . rest) ...) do?

    The dot before the last parameter makes it a rest parameter that holds a list of extra arguments.
  2. 2. What does (apply + 1 2 '(3 4)) return?

    It is the same as (+ 1 2 3 4), which is 10.
  3. 3. Which idiom transposes a list of rows?

    Applying map to all the rows walks them in parallel, producing columns.
  4. 4. How do you write an optional parameter with a default in Racket?

    Optional parameters are written in brackets with a default expression: [b 10].

Summary

  • A dot before the last parameter collects extra arguments into a list; (lambda args ...) takes everything.
  • apply calls a function with a list of arguments, the inverse of a rest parameter.
  • Rest parameters plus apply make wrappers that work for any arity.
  • Real Racket also has optional parameters [b 10] and keyword arguments #:name.
  • You now have the functional core; the next chapters add tail calls, continuations and macros.

Next: Tail Calls and Loops