Skip to content

How can a binding be a constant when symbol can be redefined? #1442

Answered by subsetpark
joeljuca asked this question in Q&A
Discussion options

You must be logged in to vote

In the simplest terms: variables bound with var can be set, and those bound with def cannot. Here's a REPL session:

Janet 1.32.1-a93517f linux/x64/gcc - '(doc)' for help
repl:1:> (def const 10)
10
repl:2:> (defn f [] (print const))
<function f>
repl:4:> (f)
10
nil
repl:5:> (def const 11)
11
repl:6:> (f)
10
nil
repl:8:> (var not-const 10)
10
repl:9:> (defn g [] (print not-const))
<function g>
repl:10:> (g)
10
nil
repl:11:> (set not-const 11)
11
repl:12:> (g)
11
nil

You see that when we define our functions f and g, we close over the variables const and not-const. This means that when we rebind the symbol const, as in repl:5, the closed-over variable inside of f is unchanged; (f) prints ou…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@joeljuca
Comment options

Answer selected by joeljuca
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants