liveBook · Manning

Unquote-splicing

As explained in Clojure: The Essential Reference

Unquote-splicing is syntax inside a syntax-quote expression that evaluates a collection and inserts its elements into an enclosing collection.

Unquote-splicing (`~@`) inserts the elements of an evaluated collection into a surrounding collection inside syntax-quote. It is useful when a macro must place several forms into generated code. Unlike unquote (`~`), it does not insert the collection as one element. section 4.1

Insert elements, not a collection

`[1 2 ~[3 4] ~@[3 (+ 1 2)]] ;; [1 2 [3 4] 3 3] Unquote keeps `[3 4]` intact; unquote-splicing inserts the two evaluated elements. section 4.1

Splicing needs a surrounding syntax-quoted collection and a value that can supply elements. Using `~@` outside syntax-quote, splicing a keyword, or placing it without a surrounding collection produces errors. In a macro body, `~@body` places supplied forms into the generated expression. section 4.1

How Clojure: The Essential Reference covers it

How deep it goes
Works through a vector result and shows errors for invalid placement and a non-sequenceable value.
Examples
Shows vector splicing, three invalid expressions, and macros that splice body forms.
What it assumes
Introduces syntax-quote and unquote before demonstrating splicing; uses Clojure collection and macro notation.
What you can do after
Apply it via Clojure syntax-quote to insert collection elements or macro body forms into generated code.
How it connects
Connects syntax-quote, unquote, and macros through generated collections of forms.

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.