destructuring-bind
destructuring-bind Macro
Syntax:
destructuring-bind lambda-list expression {declaration}* {form}*
→ {result}*
Arguments and Values:
lambda-list—a destructuring lambda list.
expression—a form.
declaration—a declare expression; not evaluated.
forms—an implicit progn.
results—the values returned by the forms.
Description:
destructuring-bind binds the variables specified in lambda-list to the corresponding values in the tree structure resulting from the evaluation of expression; then destructuring-bind evaluates forms.
The lambda-list supports destructuring as described in Section 3.4.5 (Destructuring Lambda Lists).
Examples:
(defun iota (n) (loop for i from 1 to n collect i)) ;helper
(destructuring-bind ((a &optional (b ’bee)) one two three)
‘((alpha) ,@(iota 3))
(list a b three two one)) → (ALPHA BEE 3 2 1)
Data and Control
Exceptional Situations:
If the result of evaluating the expression does not match the destructuring pattern, an error of type error should be signaled.
See Also:
macrolet, defmacro
Expanded Reference: destructuring-bind
Basic destructuring of a flat list
destructuring-bind binds variables to the corresponding elements of a list.
(destructuring-bind (a b c) '(1 2 3)
(list a b c))
=> (1 2 3)
Nested destructuring
The lambda list can mirror the tree structure of the data.
(destructuring-bind ((a b) (c d)) '((1 2) (3 4))
(+ a b c d))
=> 10
(destructuring-bind (name (year month day)) '("Alice" (1990 6 15))
(format nil "~A was born ~D/~D/~D" name month day year))
=> "Alice was born 6/15/1990"
Using &optional and &rest
destructuring-bind supports the full destructuring lambda list syntax, including &optional, &rest, and &key.
(destructuring-bind (a &optional (b 10)) '(1)
(list a b))
=> (1 10)
(destructuring-bind (first &rest others) '(a b c d)
(list first others))
=> (A (B C D))
Using &key for keyword destructuring
(destructuring-bind (&key name age) '(:age 30 :name "Bob")
(format nil "~A is ~D years old" name age))
=> "Bob is 30 years old"
Combining positional and keyword arguments
(destructuring-bind (op &key (verbose nil)) '(run :verbose t)
(list op verbose))
=> (RUN T)
Dotted pair destructuring
The lambda list can use dotted pair notation to bind the cdr of a list.
(destructuring-bind (a . b) '(1 2 3)
(list a b))
=> (1 (2 3))
(destructuring-bind (a b . c) '(1 2 3 4 5)
(list a b c))
=> (1 2 (3 4 5))