Variadic Functions in Lisp

Here’s the example of variadic functions translated to Lisp:

Variadic Functions

Variadic functions can be called with any number of trailing arguments. For example, print is a common variadic function.

Here’s a function that will take an arbitrary number of integers as arguments.

(defun sum (&rest nums)
  (print nums)
  (let ((total 0))
    (dolist (num nums)
      (incf total num))
    (print total)))

Within the function, the type of nums is equivalent to a list of integers. We can call length, iterate over it with dolist, etc.

Variadic functions can be called in the usual way with individual arguments.

(sum 1 2)
(sum 1 2 3)

If you already have multiple args in a list, apply them to a variadic function using apply like this.

(let ((nums (list 1 2 3 4)))
  (apply #'sum nums))

To run the program, put the code in a Lisp file and use a Lisp interpreter or compiler to execute it.

$ clisp variadic-functions.lisp
(1 2)
3
(1 2 3)
6
(1 2 3 4)
10

Another key aspect of functions in Lisp is their ability to form closures, which we’ll look at next.