Created
July 6, 2018 15:34
-
-
Save bhb/d82fcf0f80f555c28afa8db320be16c8 to your computer and use it in GitHub Desktop.
`set!` vs `alter-var-root`
This file contains hidden or 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
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