Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Functions and Higher-Order Functions

Destructuring in Clojure: Vectors, Maps and Nesting

Pull data apart directly in let, fn and loop bindings: sequential destructuring with & and :as, map destructuring with :keys, :strs, :or, namespaced keys, nesting and keyword arguments.

Destructuring lets you name the parts of a collection right where you bind it, instead of calling first, nth or get on every access. It works anywhere a name is bound: let, function parameters, loop, doseq, for and defn. It is one of the features that make Clojure code short and readable.

Sequential destructuring

Use a vector pattern to bind names to elements by position:

CLOJURE
(let [[a b c] [10 20 30]]
  (+ a b c))                  ; 60

(let [[first-item second-item] ["x" "y" "z"]]
  [first-item second-item])   ; ["x" "y"]

Extra elements are ignored and missing ones are nil:

CLOJURE
(let [[a b] [1]]       [a b])   ; [1 nil]
(let [[a b] [1 2 3 4]] [a b])   ; [1 2]

Three more tools: _ ignores a position, & collects the rest, and :as names the whole collection:

CLOJURE
(let [[_ second] [1 2 3]]         second)      ; 2
(let [[head & tail] [1 2 3 4]]    [head tail]) ; [1 (2 3 4)]
(let [[a b :as all] [1 2 3]]      [a b all])   ; [1 2 [1 2 3]]

Sequential destructuring works on any sequential thing: lists, vectors, strings, lazy sequences and Java arrays.

JS Stand-in: array destructuring

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Map destructuring

A map pattern binds names to values by key. The simplest form lists names as keys:

CLOJURE
(let [{name :name age :age} {:name "Ada" :age 36}]
  (str name " is " age))      ; "Ada is 36"

Writing each name twice is repetitive, so the shortcut :keys takes a vector of names and looks each one up by the keyword of the same name:

CLOJURE
(let [{:keys [name age]} {:name "Ada" :age 36}]
  (str name " is " age))      ; "Ada is 36"

The related forms:

CLOJURE
{:keys [a b]}              ; keyword keys  :a :b
{:strs [a b]}              ; string keys   "a" "b"
{:syms [a b]}              ; symbol keys   'a 'b
{:keys [user/id]}          ; namespaced key :user/id, binds the name id
{:user/keys [id name]}     ; all keys in the namespace user
{:keys [a] :or {a 0}}      ; default value when :a is missing
{:keys [a] :as m}          ; also bind the whole map to m

Defaults with :or apply only when the key is absent, not when its value is nil or false:

CLOJURE
(let [{:keys [port] :or {port 80}} {}]            port)   ; 80
(let [{:keys [port] :or {port 80}} {:port nil}]   port)   ; nil

As function parameters

The same patterns work directly in a defn parameter list:

CLOJURE
(defn full-name [{:keys [first-name last-name]}]
  (str first-name " " last-name))

(full-name {:first-name "Ada" :last-name "Lovelace"})   ; "Ada Lovelace"

(defn describe [[x y] {:keys [label] :or {label "point"}}]
  (str label " at " x "," y))

(describe [3 4] {:label "origin"})   ; "origin at 3,4"
JS Stand-in: object destructuring with defaults

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Nested destructuring

Patterns can be nested to any depth, mixing vectors and maps:

CLOJURE
(def order
  {:id 7
   :customer {:name "Ada" :address {:city "London"}}
   :items [{:sku "A1"} {:sku "B2"}]})

(let [{:keys [id]
       {:keys [name] {:keys [city]} :address} :customer
       [first-item] :items} order]
  [id name city first-item])
;; => [7 "Ada" "London" {:sku "A1"}]

The inner pattern goes where the key's name would go: {pattern :key}. When patterns get this dense, it is clearer to use get-in (see Working with Nested Data) or to destructure in two steps. Use nesting for two levels, not five.

Destructuring in loops and comprehensions

Destructuring is especially useful when iterating over map entries or pairs:

CLOJURE
(doseq [[k v] {:a 1 :b 2}]
  (println k "->" v))

(for [[name score] [["Ada" 90] ["Grace" 95]]
      :when (> score 92)]
  name)                          ; ("Grace")

(map (fn [[a b]] (+ a b)) [[1 2] [3 4]])   ; (3 7)
(map (fn [{:keys [qty price]}] (* qty price))
     [{:qty 2 :price 3} {:qty 1 :price 10}])   ; (6 10)

Keyword arguments (rest as a map)

You can destructure the variadic & rest arguments as a map. Callers then pass key-value pairs:

CLOJURE
(defn start-server [& {:keys [port host] :or {port 8080 host "localhost"}}]
  (str host ":" port))

(start-server)                         ; "localhost:8080"
(start-server :port 3000)              ; "localhost:3000"
(start-server :host "0.0.0.0" :port 9000)

In Clojure 1.11 and later, a trailing map can also be passed to such a function. This style is less common than an options map, but you will meet it in older libraries.

A swap and other idioms

CLOJURE
(let [[a b] [1 2]
      [a b] [b a]]
  [a b])          ; [2 1]   rebind, do not mutate

(let [[q r] ((juxt quot rem) 17 5)]
  [q r])          ; [3 2]   functions returning pairs

Destructuring cheat sheet

[a b & more] By position, rest in more.
{:keys [a b]} Keyword keys by name.
:or {a 0} Defaults for missing keys.
:as whole Keep the entire value too.

Works in let, fn, loop, doseq and for.

1 / 2

Common mistakes

  • Expecting :or to replace nil values. It replaces only missing keys.
  • Using :keys on a map with string keys: use :strs.
  • Forgetting that missing positions in a vector pattern become nil, not an error.
  • Over-nesting patterns until nobody can read them.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (let [[a & more] [1 2 3]] more) return?

    & collects the rest into a sequence, printed as (2 3).
  2. 2. Which pattern binds name and age from a map with those keyword keys?

    {:keys [...]} looks each name up as a keyword key.
  3. 3. When does an :or default apply?

    :or applies when the key is absent, not when it is present with a nil value.
  4. 4. What does (let [[a b] [1]] b) return?

    Missing positions are bound to nil.

Summary

  • Destructuring binds parts of a collection by pattern in let, fn, loop, doseq and for.
  • Vector patterns bind by position and support & for the rest and :as for the whole.
  • Map patterns use {:keys [a b]}, :strs, :syms, :or defaults and :as.
  • Nest patterns for two levels, then switch to get-in for clarity.
  • Use & {:keys [...]} for keyword arguments.

Next: Higher-Order Functions