~ / track A / clojure basics

Destructuring

Basic

Destructuring 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:

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

Map destructuring matches by key. :keys is the shorthand when the local name equals the key:

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

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.

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

Nested destructuring composes — match shapes inside shapes:

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

Useful options

  • :as binds the whole input too: {:keys [a b] :as m} gives you a, b, and m.
  • :or provides defaults for missing keys.
  • Vector destructuring supports :as: [a b :as v].
loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate

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).

loading sci
press ⌘/Ctrl-↵ or click ▶ run to evaluate
 status: new