When use hash function with ref object hashset not working correctly(if i remove ref (like pointer) its ok) , but when i've add == (equal) overload function its working perfect. How is nim language compare to pointer object? does it use adress of memory or something like that?
Example code like this:
type NM = ref object of RootObj
name*:string
# i added this for working correctly
proc `==` (a,b: NM):bool =
a.name == b.name
proc hash(nm:NM):Hash =
return !$nm.name.hash
proc `$`(nm:NM):string =
return nm.name & " hash: " & $nm.hash
var b = initHashSet[NM]()
var
f = NM(name: "XX")
g = NM(name: "YY")
h = NM(name: "XX")
b.incl(f)
b.incl(g)
b.incl(f)
b.incl(g)
# b.incl(h)
echo b.contains(h)
echo $b
You are not telling us what your desired result is!
Do you expect b.contains(h) to be false or true?
Of course h is a different object, even when it field name has same value as other objects already included to set.
My assumption is that default hash is based on address of ref objects, so objects are different by default. To make objects of different addresses equal when name is equal, you have to redefine hash() and == procs. But I can not remember details and I may confuse that with other programming languages, you may have to consult the api docs.
Thanks for answer, but for clarification: > Do you expect b.contains(h) to be false or true?
I except result must be true, because if object referenced or not, hashset must to look up hash function result.
Indeed if i used another type rather than object they couldn't be share some memory location.
i dig in source code a bit. It looks like search by "for x in list" like statement. so i added equal overload function. But if compiler doesn't look the hash function why it gives me error? Or how can i compare two object? Some languages like java (as i can remember) it looks hashes for compare. But in nim it doesn't use for compare object
echo f == h # --> result false
Interesting. But i don't know it's a bug or feature.
I except result must be true,
I have some problems understanding your English unfortunately...
I think Nim's hashing concept is explained in the tables module, see
https://nim-lang.org/docs/tables.html#basic-usage-hashing
maybe that explaination is missing in the hashset module.