alter-var-root

added
1.0

ns
clojure.core

type
function

(alter-var-root v f & args)

Atomically alters the root binding of var v by applying f to its
current value plus any args

                (defn sqr [n] 
  "Squares a number"
  (* n n))

user=> (sqr 5)
25

user=> (alter-var-root 
         (var sqr)                     ; var to alter
         (fn [f]                       ; fn to apply to the var's value
           #(do (println "Squaring" %) ; returns a new fn wrapping old fn
                (f %))))

user=> (sqr 5)
Squaring 5
25

            
                ;;change the value of a var, instead of (def varName value)
user=> (def string "abcd")
#'user/string

user=> string
"abcd"

user=> (alter-var-root #'string (constantly "wxyz"))
"wxyz"

user=> string
"wxyz"