Skip to content

immutability with var and def #1234

Answered by CosmicToast
MarcusE1W asked this question in Q&A
Discussion options

You must be logged in to vote

It is different.
In the case of a, you have an immutable binding with mutable data.
In the case of b, you have a mutable binding with mutable data.
The mutability of the binding vs the data really have nothing to do with one another.
Here is another example:

(def a @[1 2 3])
(defn addx [x] (array/push a x))
(defn prnx [] (pp a))
(addx 4) # a is @[1 2 3 4]
(prnx) # => @[1 2 3 4]
(def a @[1]) # a is @[1], but the old capture is still valid
(addx 5) # the new a is a different binding, it was not modified
(prnx) # => @[1 2 3 4 5] since the old binding is still captured

On the converse, the same with mutable bindings:

(var a @[1 2 3])
(defn addx [x] (array/push a x))
(defn prnx [] (pp a))
(addx 4

Replies: 1 comment 4 replies

Comment options

You must be logged in to vote
4 replies
@CosmicToast
Comment options

@MarcusE1W
Comment options

@CosmicToast
Comment options

Answer selected by MarcusE1W
@MarcusE1W
Comment options

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