<aside>
💡 Local definitions (written in the format (local [<defintions>] <expressions>)
) should be used whenever…
Forming local definitions is a 3-step process —
Locally-defined objects have a restricted scope and are typically inaccessible to objects in the global scope.
</aside>
For instance,
(define a 1)
(define b 2)
(local [(define a 3)
(define b 4)]
(+ a b))
(+ a b)
;; (+ a b) in the local expression returns 7 (a = 3, b, 4).
;; (+ a b) in the global scope returns 3 (a = 1, b = 2).
<aside> 🔍 Another discussion of lexical scoping through University of Washington’s Programming Languages course can be found here.
</aside>
a
and b
from the local expression (black box that locally defines b
).
b
is defined as 3
while a
is undefined. As such, the compiler searches for a
in the scope where the local expression was defined — the global scope.a
is defined as 1
. Therefore, the local function (+ a b)
evaluates to 4
since it takes the local definition of b
(3
)and the global definition of a
(1
).(+ a (local [(define b 3)] (+ a b)) b)
, however, the global definitions of a
(1
) and b
(2
) are used. Therefore, the expression evaluates to (+ 1 4 2)
= 7
.