Lexical and Dynamic Scope Usage

Do you keep forgetting the difference between lexical and dynamic scoping? Perhaps it helps to think about when you would pick one over the other.

Image for post
Image for post
A rifle scope which has absolutely nothing to do with scopes in programming languages ;-) But it looks really cool.

of or relating to the words or vocabulary of a language, especially as distinguished from its grammatical and syntactical aspects.

Enough Musings! Give Me a Code Example!

v = a*t + v0
a  = 4
v0 = 10
velocity(t) = a*t + v0
julia> velocity(1)
14
julia> velocity(2)
18
julia> v0 = 100
100
julia> velocity(1)
104
julia> v0 = 0
0
julia> velocity(1)
4
function moon_velocity(t)
a = 10
v0 = 100
return velocity(t)
end
julia> moon_velocity(1)
4
function make_velocity(a, v0)
return function(t)
a*t + v0
end
end
velocity = make_velocity(4, 10)moon_velocity = make_velocity(10, 100)

When Do You Want Dynamic Scope?

Dynamic Scope for Loggers

logger.warning("something bad happened, fix it!")
function inner_dummy(x)
@info "my log message" x
end
function outer_dummy(x)
inner_dummy(x)
with_logger(Logging.global_logger()) do
inner_dummy(x+10)
end
end
io = open("log.txt", "w+")
logger = SimpleLogger(io)
with_logger(logger) do
@info "hello world"
outer_dummy(3)
end
close(io)
┌ Info: my log message
└ x = 13
┌ Info: hello world
└ @ Main REPL[9]:2
┌ Info: my log message
│ x = 3
└ @ Main REPL[2]:2

Conclusion, You Need Both

Written by

Geek dad, living in Oslo, Norway with passion for UX, Julia programming, science, teaching, reading and writing.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store