Cl

Closures in Clojure

2 exercises

About Closures

Closures are a programming pattern in Clojure which allows variables from an outer lexical scope to be used inside of a function. Clojure supports closures transparently, and they are often used without knowing what they are.

;; Top-level definitions are global-scope
(def dozen 12)

;; Functions create a new scope.
;; Referencing the outer variable here is a closure.
(fn [n] (* dozen n))

Closures to save state and pass along values

Using an atom allows for some state to be preserved:

;; This function closure increments the counter's state
;; in the outer lexical context.
;; This way the counter can be shared between many calling contexts.

(def increment
  (let [counter (atom 0)]
    (fn [] (swap! counter inc))))

Each successive call to increment increments its counter:

(increment)
;;=> 1
(increment)
;;=> 2
Edit via GitHub The link opens in a new window or tab

Learn Closures