clojure and ^:dynamic

前端 未结 1 844
轻奢々
轻奢々 2020-12-29 03:24

I tried to understand dynamic variables and binding function so I tried this (clojure 1.3):

user=> (defn f [] 
           (def ^:dynamic x 5) 
                    


        
相关标签:
1条回答
  • 2020-12-29 04:11

    I get 3 as a result (as you would expect) when I run your first example in Clojure 1.4.... have you tried this with a fresh REPL?

    ^:dynamic is an instruction to the Clojure compiler that a symbol (as defined with def) is intended to be dynamically rebound (with binding).

    Example:

    (def foo 1)
    (binding [foo 2] foo)
    => IllegalStateException Can't dynamically bind non-dynamic var: ...
    
    (def ^:dynamic bar 10)
    (binding [bar 20] bar)    ;; dynamically bind bar within the scope of the binding
    => 20
    bar                       ;; check underlying value of bar (outside the binding)
    => 10
    

    Note that binding has dynamic scope within the calling thread - any functions called within the binding will see the modified value of bar (20), but any other threads will still see the unchanged root value of 10.

    Finally a couple of style points that you may find helpful:

    • It's generally considered bad idea to put def and defn within functions as they affect the enclosing namespace. Within functions you should use (let [foo bar] ...) instead.
    • When you find yourself wanting to use binding you should normally consider whether you can achieve the same result using higher order functions instead. binding is useful in some contexts but it is not in general a good way to pass parameters around - function composition is usually better in the long run. The reason for this is that binding creates an implicit context that is required for the execution of your function and this can be difficult to test/debug.
    0 讨论(0)
提交回复
热议问题