Created
March 24, 2017 17:28
-
-
Save seancorfield/fec987825058a681c9ce4f9b22519edc to your computer and use it in GitHub Desktop.
Example of closures in Clojure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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