My ImmutableDict Changes Its Values

Is this correct? When I change some of the values in the last variable used to assign a key-val pair to the ImmutableDict the values in the immutable dictionary are changing. Is this a bug or correct behavior? Is so, then I guess I’ll try pushing NamedTuples into an array or something else.

My console output:

> julia> versioninfo()
> Julia Version 1.6.5
> Commit 9058264a69 (2021-12-19 12:30 UTC)
> Platform Info:
>   OS: Windows (x86_64-w64-mingw32)
>   CPU: Intel(R) Core(TM) i5-8365U CPU @ 1.60GHz
>   WORD_SIZE: 64
>   LIBM: libopenlibm
>   LLVM: libLLVM-11.0.1 (ORCJIT, skylake)
> Environment:
>   JULIA_NUM_THREADS = 4
> 
> julia> include("c:/jl/test_immutable.jl")
> Everything is fine...
> 10.0 => Bool[0, 1, 1, 0, 0, 0, 1]
> 9.0 => Bool[1, 0, 1, 0, 0, 0, 1]
> 8.0 => Bool[1, 0, 1, 0, 0, 0, 0]
> But then we change the boolean values of yVals using an index...
> ...and now the last entry has changed
> 10.0 => Bool[0, 0, 0, 0, 0, 0, 1]
> 9.0 => Bool[1, 0, 1, 0, 0, 0, 1]
> 8.0 => Bool[1, 0, 1, 0, 0, 0, 0]
> Is this correct that the ImmutableDict can be changed in this way?

My MWE code:

ImmD = Base.ImmutableDict{Float64, Vector{Bool}}

xKey = 8.0
yVals = Bool[1,0,1,0,0,0,0]
ImmD = Base.ImmutableDict(xKey=>yVals)

xKey = 9.0
yVals = Bool[1,0,1,0,0,0,1]
ImmD = Base.ImmutableDict(ImmD, xKey=>yVals)

xKey = 10.0
yVals = Bool[0,1,1,0,0,0,1]
ImmD = Base.ImmutableDict(ImmD, xKey=>yVals)

println("Everything is fine...")
foreach(println, ImmD)


println("But then we change the boolean values of yVals using an index...")
yVals[2] = 0
yVals[3] = 0

println("...and now the last entry has changed")
foreach(println, ImmD)

println("Is this correct that the ImmutableDict can be changed in this way?")

The Dict is immutable, not the values in it. Those are mutable arrays and you’ve mutated some of them.

1 Like