Skip to content

Instantly share code, notes, and snippets.

@bhb
Created July 6, 2018 15:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhb/d82fcf0f80f555c28afa8db320be16c8 to your computer and use it in GitHub Desktop.
Save bhb/d82fcf0f80f555c28afa8db320be16c8 to your computer and use it in GitHub Desktop.
`set!` vs `alter-var-root`
Clojure 1.9.0
user=> (def ^:dynamic *x* "foo")
#'user/*x*
user=> *x*
"foo"
user=> ;; binding changes value
user=> (binding [*x* "bar"] *x*)
"bar"
user=> ;; using set! within binding changes value
user=> (binding [*x* "bar"] (set! *x* "bar") *x*)
"bar"
user=> ;; using alter-var-root outside of binding changes value
user=> (alter-var-root #'*x* (constantly "baz"))
"baz"
user=> *x*
"baz"
user=> (alter-var-root #'*x* (constantly "foo"))
"foo"
user=> ;; but using alter var root inside a binding doesn't show up within binding
user=> ;; since the binding value takes precedence
user=> (binding [*x* "bar"] (alter-var-root #'*x* (constantly "baz")) *x*)
"bar"
user=> ;; of course in the outer scope, the change has been applied
user=> *x*
"baz"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment