multiple-value-setq
multiple-value-setq Macro
Syntax:
multiple-value-setq vars form ! result
Arguments and Values:
vars—a list of symbols that are either variable names or names of symbol macros.
form—a form.
result—The primary value returned by the form.
Description:
multiple-value-setq assigns values to vars.
The form is evaluated, and each var is assigned to the corresponding value returned by that form. If there are more vars than values returned, nil is assigned to the extra vars. If there are more values than vars, the extra values are discarded.
If any var is the name of a symbol macro, then it is assigned as if by setf. Specifically, (multiple-value-setq (symbol1 ... symboln) value-producing-form)
is defined to always behave in the same way as
(values (setf (values symbol1 ... symboln) value-producing-form))
in order that the rules for order of evaluation and side-e↵ects be consistent with those used by setf. See Section 5.1.2.3 (VALUES Forms as Places).
Examples:
(multiple-value-setq (quotient remainder) (truncate 3.2 2)) *!* 1
quotient *!* 1
remainder *!* 1.2
(multiple-value-setq (a b c) (values 1 2)) *!* 1
a *!* 1
b *!* 2
c *!* NIL
(multiple-value-setq (a b) (values 4 5 6)) *!* 4
a *!* 4
b *!* 5
See Also:
setq, symbol-macrolet
Data and Control
Expanded Reference: multiple-value-setq
Basic usage: capturing multiple return values
multiple-value-setq assigns multiple return values to existing variables. It returns only the primary value.
(let (quotient remainder)
(multiple-value-setq (quotient remainder) (floor 17 5))
(list quotient remainder))
=> (3 2)
More variables than values
If there are more variables than values returned, the extra variables are set to NIL.
(let (a b c)
(multiple-value-setq (a b c) (values 1 2))
(list a b c))
=> (1 2 NIL)
Fewer variables than values
If there are more values than variables, the extra values are discarded.
(let (a b)
(multiple-value-setq (a b) (values 1 2 3 4))
(list a b))
=> (1 2)
Return value is the primary value
multiple-value-setq itself returns only the primary value of the form.
(let (a b)
(multiple-value-setq (a b) (truncate 3.7)))
=> 3
Using with gethash
A practical use case is capturing both the value and the found-p flag from gethash.
(let ((ht (make-hash-table))
value found-p)
(setf (gethash 'x ht) 42)
(multiple-value-setq (value found-p) (gethash 'x ht))
(list value found-p))
=> (42 T)
Assigning to special variables
multiple-value-setq works with previously declared variables, including special variables.
(defvar *q*)
(defvar *r*)
(multiple-value-setq (*q* *r*) (floor 100 7))
=> 14
*q* → 14
*r* → 2