Functions and Scopes - 1

Home

The body of a function is a new scope. In side this new scope, we can refer to symbols. We will look at different types of symbols that are available inside a function.

Local bindings & parameters

(defn f [x y]
  (let [a 1]
    (+ a x y)))

(f 2 3) ;=> 6

The local symbol a and the parameters x and y are available.

Symbols from outside the function

We can “capture” symbols from outside the function. This is also called closure. There are two different rules on how we can capture symbols from outside the function.

The Lexical Scoping Rule

According to this rule, all symbols that were available in the scope where the function is defined are available to the function forever.

(let [tax-rate 0.1]
  (defn calc-tax [income]
    (* tax-rate tax)))

(let [tax-rate 0.2] (calc-tax 1000))
; => 100

The body of calc-tax does not declare tax-rate, but it inherited the symbol from scope of function declaration, not scope of function invocation.

Ken Pu
Thursday, Apr 5, 2018

comments powered by Disqus