What does ^: dynamic do in Clojure?

I searched for “clojure dynamic” and “clojure dynamic scope” and read over 10 articles, and I still don't understand what it is doing ^:dyanmic. I think this article may answer my question , but the code samples seem to be "missing", so I'm not even sure if this refers to the same thing, confused.

I am trying to fix a problem in a clj-http project , but first I need to understand the code. It has functions defined as follows:

(defn ^:dynamic parse-html
  "Resolve and apply crouton HTML parsing."
  [& args]
  {:pre [crouton-enabled?]}
  (apply (ns-resolve (symbol "crouton.html") (symbol "parse")) args))

But I do not understand what it means ^:dynamic. Can someone explain this to me in a very simple way?

+5
source share
1 answer

It defines a function as dynamically bounded.

, - parse-html , .

parse-html , , , parse-html, , , .

. "let current_numeric_base = 16; "; . , , , , . http://c2.com/cgi/wiki?DynamicScoping


, , Clojure. , , , , , , .

, , - .

:

(def ^:dynamic a 0)

(defn some-func [x] (+ x 1))

; re-binds a to 1 for everything in the callstack from the (binding)
; call and down
(binding [a 1] 
   (print (some-func a)))

 ; a was only re-bound for anything that was called from
 ; within binding (above) so at this point a is bound to 0.
(print (some-func a))

: 2 1

:

(def a 0)

(defn some-func [x] (+ x 1))

; re-binds a to 1 for everyone, not just things that 
; are in the callstack created at this line
(set-var [a 1]  ; set-var is a made up function that can re-bind lexically scoped variables
   (print (some-func a)))

; a was lexically scoped so changing it changed
; it globally and not just for the callstack that
; contained the set-var.
(print (some-func a))

: 2 2

+7

All Articles