Functions

Named Functions

You define functions using the defun macro:

(defun fib (n)
  "Return the nth Fibonacci number."
  (if (< n 2)
      n
      (+ (fib (- n 1))
         (fib (- n 2)))))

And call them like you call anything else:

CL-USER> (fib 30)
832040

Anonymous Functions

Application

Functions can be called indirectly using funcall:

CL-USER> (funcall #'fib 30)
832040

Or with apply:

CL-USER> (apply #'fib (list 30))
832040

Multiple Return Values

(defun many (n)
  (values n (* n 2) (* n 3)))
CL-USER> (multiple-value-list (many 2))
(2 4 6)

CL-USER> (nth-value 1 (many 2))
4

We can also use multiple-value-bind to assign each return value to a variable:

CL-USER> (multiple-value-bind (first second third)
             (many 2)
           (list first second third))
(2 4 6)