liveBook · Manning

Gensym

As explained in Clojure: The Essential Reference

gensym is a Clojure function that generates a unique symbol, typically for avoiding name collisions in macro-generated code.

gensym returns a unique Clojure symbol, mainly helping macro authors avoid accidental symbol capture when syntax-quote does not provide enough automatic generation. section 4.0 section 4.4

Its contract is small:

  • Call (gensym) to use the default G__ prefix. section 4.4
  • Call (gensym "prefix") to choose a prefix string. section 4.4
  • Receive a symbol whose name combines the prefix with a number unique in the current Java instance. section 4.4

Generating names for transformed expressions

(gensym) ; => G__14 (gensym "my-prefix") ; => my-prefix17 A logic-expression transformation can bind a fresh local instead of reusing an existing variable: (pull-quantifier '(OR (EXIST x (Q x)) (P x))) ;; => (EXIST local2747 (OR (P x) (Q local2747))) The generated local prevents the moved quantifier from capturing the wrong x. section 4.4 section 4.4

(gensym) ; #1
;; G__14

(gensym "my-prefix") ; #2
;; my-prefix17

Inspect representative default- and custom-prefix results from gensym. section 4.4

How Clojure: The Essential Reference covers it

How deep it goes
Defines arity, prefix behavior, output shape, uniqueness scope, and a worked variable-capture transformation.
Examples
Uses default and custom prefixes plus a quantified-logic transformation that introduces fresh local symbols.
What it assumes
Assumes familiarity with Clojure symbols and macros while demonstrating accidental capture through a logic-expression example.
What you can do after
Apply it via Clojure to generate collision-resistant symbols for macro-generated forms or other uniquely labeled expressions.
How it connects
Connects macros, syntax-quote, macro hygiene, symbol capture, and symbolic expression 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.