Skip to content

Instantly share code, notes, and snippets.

@seancorfield
Created March 24, 2017 17:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seancorfield/fec987825058a681c9ce4f9b22519edc to your computer and use it in GitHub Desktop.
Save seancorfield/fec987825058a681c9ce4f9b22519edc to your computer and use it in GitHub Desktop.
Example of closures in Clojure
(defn do-it []
(let [a ["a" "b" "c"]
b ["x" "y" "z"]
counter (atom 0)]
(run! (fn [foo]
(reset! counter 0)
(run! (fn [bar]
(swap! counter inc)
(println {:counter @counter
:foo foo
:bar bar}))
b))
a)))
;; output
{:counter 1, :foo a, :bar x}
{:counter 2, :foo a, :bar y}
{:counter 3, :foo a, :bar z}
{:counter 1, :foo b, :bar x}
{:counter 2, :foo b, :bar y}
{:counter 3, :foo b, :bar z}
{:counter 1, :foo c, :bar x}
{:counter 2, :foo c, :bar y}
{:counter 3, :foo c, :bar z}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment