Multiple Return Values in Lisp

(defun vals ()
  (values 3 7))

(defun main ()
  (multiple-value-bind (a b) (vals)
    (format t "~a~%" a)
    (format t "~a~%" b))
  
  (multiple-value-bind (_ c) (vals)
    (declare (ignore _))
    (format t "~a~%" c)))

Lisp has built-in support for multiple return values. This feature is often used in idiomatic Lisp, for example to return both result and error values from a function.

The (values 3 7) in the vals function shows that the function returns 2 integers.

In the main function:

(multiple-value-bind (a b) (vals)
  (format t "~a~%" a)
  (format t "~a~%" b))

Here we use the 2 different return values from the call with multiple-value-bind, which is Lisp’s way of handling multiple assignment.

(multiple-value-bind (_ c) (vals)
  (declare (ignore _))
  (format t "~a~%" c))

If you only want a subset of the returned values, you can use the underscore _ as a placeholder and declare it as ignored. This is similar to using the blank identifier in other languages.

To run the program:

$ sbcl --script multiple-return-values.lisp
3
7
7

Returning multiple values is a powerful feature in Lisp that allows for expressive and efficient code. We’ll explore more Lisp features in the upcoming examples.