Variadic Functions in Racket

Here’s a function that will take an arbitrary number of ints as arguments in Racket.

#lang racket

(define (sum . nums)
  (display nums)
  (newline)
  (let ((total 0))
    (for ([num nums])
      (set! total (+ total num)))
    (displayln total)))

(sum 1 2)
(sum 1 2 3)

(let ((nums '(1 2 3 4)))
  (sum @nums))

To run the program, simply execute the script with Racket.

$ racket variadic-functions.rkt
'(1 2)
3
'(1 2 3)
6
'(1 2 3 4)
10

In this example, the sum function is defined to accept a variable number of arguments using the dot notation (.). Inside the function, the variable nums is a list containing all the provided arguments. The for loop iterates over the list, summing up the values. Finally, the results are printed.

Next, we’ll explore another key aspect of functions in Racket: their ability to form closures.