Functions and Scopes - 2

Home

Dynamic variables are symbols that can be temporally bound to a new value, and the binding propagates into the body of a function. This pattern is known as dynamic scopes, and is generally considered as a bad idea. Nonetheless, here it is.

The use of COBOL cripples the mind; its teaching should, therefore, be regarded as a criminal offense. Edsger W. Dijkstra

Declaration of dynamic var

Dynamic vars are special symbols. Unlike other symbols, their bindings can be changed in the same scope.

(def ^:dynamic tax-rate 0.1)
(defn calc-tax [income] (* tax-rate income))

The dynamic var acts as a normal symbol, and is captured by the lexical rule.

(calc-tax 1000) ; => 100.0

Dynamic binding

But the existing binding of a dynamic var can be modified.

(binding [tax-rate 0.15]
  (calc-tax 1000)) ;=> 150.0

This is something that (let ...) cannot achieve:

(let [tax-rate 0.15]
  (calc-tax 1000)) ;=> 100.0

Ken Pu
Thursday, Apr 5, 2018

comments powered by Disqus