gpt4 book ai didi

julia - 为什么 push!() 向 Set 添加重复元素?

转载 作者:行者123 更新时间:2023-12-04 23:41:19 26 4
gpt4 key购买 nike

使用 Set 时Julia 中的复合类型,push!函数似乎将重复的项目添加到集合中。阅读 Julia 标准文档,我假设 isequal函数将用于测试重复项。我想我误解了,所以也许有人可以帮助我。

作为示例,请参见下面的代码。我特别想知道为什么t2被添加到集合中,尽管与 t1 相同.

很感谢任何形式的帮助。注意:在我的例子中是两个 t 类型的变量如果字段 x1 被认为是相同的和 x2是平等的;其余字段的值无关紧要。

type t 

x1::Float64
x2::Float64

b1::Bool
b2::Bool

end

isequal( tx::t, ty::t) = (tx.x1 == ty.x1) && (tx.x2 == ty.x2)
==(tx::t, ty::t) = (tx.x1 == ty.x1) && (tx.x2 == ty.x2)

t1 = t( 1, 2, true, true)
t2 = t( 1, 2, true, true)
tc = t1
tdc = deepcopy( t1)

[ t1 == t2 isequal( t1, t2)] # ---> [ true true ]
[ t1 == tc isequal( t1, tc)] # ---> [ true true ]
[ t1 == tdc isequal( t1, tdc)] # ---> [ true true ]


s = Set{t}()
push!( s, t1)
push!( s, t2) # adds t2 to the set although t2 and t1 are identical ...
push!( s, tc) # does not add ...
push!( s, tdc) # adds tdc although tdc and t1 are identical

最佳答案

正如 DSM 所指出的,您只需要为 hash 添加一个方法。对于您的类型,即:

hash(x::t, h) = hash(x.x2, hash(x.x1, h))

关于julia - 为什么 push!() 向 Set 添加重复元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36957263/

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