gpt4 book ai didi

set - Julia 集在哪些方面是不可变的?

转载 作者:行者123 更新时间:2023-12-03 23:43:14 26 4
gpt4 key购买 nike

如果我在 Julia 中创建了一个集合,那么 Julia 会告诉我这个集合是不可变的。

julia> pets = Set(["dog", "cat", "budgerigar"])
Set{String} with 3 elements:
"cat"
"budgerigar"
"dog"

julia> ismutable(pets)
false
尽管如此,我可以就地修改设置。
julia> push!(pets, "orangutan")
Set{String} with 4 elements:
"orangutan"
"cat"
"budgerigar"
"dog"
我可以检查设置内容是否已更改。
julia> display(pets)
Set{String} with 4 elements:
"orangutan"
"cat"
"budgerigar"
"dog"
同样,我可以从集合中删除就地
julia> delete!(pets, "dog")
Set{String} with 3 elements:
"orangutan"
"cat"
"budgerigar"
所以我的问题是,集合在哪些方面是不可变的?与字典相比,它们的可变性有何不同?
julia> ismutable(Dict())
true
我不明白什么?

最佳答案

如果您查看 sourceSet ,你可以看到一个 Set只是 Dict{T,Nothing} 的包装器,当你添加一个新项目时,说 x::T , 到 Set , Julia 刚刚在 Dict 中创建了一个新条目的 x => nothing .也就是说,条目存储在 Dict 的键中,并且这些值不相关,因此设置为 nothing .
显然,一个 Dict正如您在问题中所观察到的那样,必须是可变的。 Set本身不需要是可变的,因为所有的变异都是在 Dict 中执行的。由 Set 包裹.要明白我的意思,我们可以弄乱 Set 的内部结构。

julia> s = Set(["a", "b"])
Set{String} with 2 elements:
"b"
"a"

julia> s.dict
Dict{String,Nothing} with 2 entries:
"b" => nothing
"a" => nothing

julia> push!(s, "c")
Set{String} with 3 elements:
"c"
"b"
"a"

julia> s.dict["d"] = nothing

julia> s.dict
Dict{String,Nothing} with 4 entries:
"c" => nothing
"b" => nothing
"a" => nothing
"d" => nothing

julia> s.dict = Dict("a new set"=>nothing)
ERROR: setfield! immutable struct of type Set cannot be changed
Stacktrace:
[1] setproperty!(::Set{String}, ::Symbol, ::Dict{String,Nothing}) at ./Base.jl:34
[2] top-level scope at REPL[14]:1
这里的关键见解是我可以使用 s.dict 的可变性。随心所欲。但是因为 Set是不可变的,我无法替代 s.dict全新 Dict .这会触发您在上面的 session 中看到的错误。
如果不清楚具有可变内部结构的不可变类型意味着什么,我几年前在 StackOverflow 上问了一个类似的问题。可以找到 here

关于set - Julia 集在哪些方面是不可变的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64529568/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com