Destructuring
BasicDestructuring is a way to bind names to parts of a value in one step. You
write the shape of the data on the left-hand side of a let or function
parameter, and Clojure pulls out the pieces by position (for vectors) or by
key (for maps). It replaces a stack of get / nth / first calls with a
single declarative pattern.
Minimal example
Vector destructuring matches by position. Use & rest to capture the tail:
Map destructuring matches by key. :keys is the shorthand when the local name
equals the key:
Practical example
Destructuring shines in function parameter lists, where it doubles as documentation: a reader can see at a glance what shape the function expects.
Nested destructuring composes — match shapes inside shapes:
Useful options
:asbinds the whole input too:{:keys [a b] :as m}gives youa,b, andm.:orprovides defaults for missing keys.- Vector destructuring supports
:as:[a b :as v].
Check yourself
? quiz
Given `(let [{:keys [a b] :or {b 99}} {:a 1}] [a b])`, what is the result?
Exercise
Write summarize that takes one map of the shape {:user {:name X :email Y} :scores [a b c]} and returns {:name X :total (+ a b c)} using only
destructuring (no get, no :user lookups in the body).