Destructuring allows you to extract data from various objects into distinct variables. In each example below, each variable is assigned to its own string (a
="a"
, b="b"
, &c.)
Type | Example | Value of data / comment |
---|---|---|
vec | (let [[a b c] data ...) | ["a" "b" "c"] |
nested vec | (let [[[a b] [c d]] data ...) | [["a" "b"] ["c" "d"]] |
map | (let [{a :a b :b c :c} data ...) | {:a "a" :b "b" :c "c"} |
— alternative: | (let [{:keys [a b c]} data ...) | When variables are named after the keys. |
Tips:
- Default values can be provided using
:or
, otherwise the default isnil
- Use
& rest
to store aseq
of any extra values inrest
, otherwise the extra values are ignored - A common and useful use of destructuring is for function parameters
- You can assign unwanted parts to a throw-away variable (conventionally:
_
)