liveBook · Manning

Destructure

As explained in Clojure: The Essential Reference

destructure is a Clojure function that transforms a binding form and an expression into bindings implementing destructuring.

destructure is an undocumented Clojure function that transforms a binding form and an expression into ordinary let bindings implementing destructuring. Macros such as fn and let use it to extend fn* and let* with destructuring support. section 4.6 section 4.9

Its input is a bindings vector containing binding-expression pairs; its output is a bindings vector containing generated symbols, nth or key lookups, aliases, and defaults. Nested vector and map forms are supported. section 4.6

The destructuring contract supports:

  • Sequential bindings over sequences, vectors, strings, Java arrays, and lists, including tail binding with & and collection aliasing with :as. section 4.6
  • Map bindings with explicit key forms, :keys, :strs, :syms, :or defaults, and :as aliases; absent values can receive defaults while present nil remains nil. section 4.6
  • Arbitrarily nested combinations of sequential and associative bindings. section 4.6

Inspecting and using the generated bindings

(destructure '[[x y] [1 2]]) ;; [vec__14 [1 2] x (nth vec__14 0 nil) y (nth vec__14 1 nil)] (eval `(let ~(destructure '[[x y] [1 2]]) (+ ~'x ~'y))) ;; 3 The result exposes destructuring as code generation: a nested binding becomes a temporary collection binding followed by ordinary element lookups.

How Clojure: The Essential Reference covers it

How deep it goes
Defines the transformation contract and demonstrates generated bindings, while leaving each destructuring case’s semantics to examples.
Examples
Uses generated vector bindings, evaluated let code, nested function arguments, sequence tails, aliases, map defaults, and nested maps and vectors.
What it assumes
Assumes familiarity with Clojure expressions and bindings while connecting the function to macro construction and special forms.
What you can do after
Evaluate and inspect how Clojure destructuring expands into ordinary binding pairs.
How it connects
Connects destructuring with macros, fn, let, fn*, let*, and source-to-source transformation.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.