How to use unique function?

Hello,

I have a vector of a type named Gate. I define == for it and I checked that isequal works as well.

I want to use the unique function, but it doesn’t seem to work.

Here a screenshot that show the problem.

08 :

The length of the vector after using unique should be 2, but it is still 4 and I don’t understand since there are in fact only 2 unique elements.

Thank!

2 Likes

You also need to implement hash(x::Gate).

1 Like

I think @anon94023334 is exactly right. In case you want to learn more, the documentation for isequal mentions that:

help?> isequal
search: isequal

  isequal(x, y)

  Similar to ==, except treats all floating-point NaN values as equal to each other, and treats -0.0 as unequal
  to 0.0. The default implementation of isequal calls ==, so if you have a type that doesn't have these
  floating-point subtleties then you probably only need to define ==.

  isequal is the comparison function used by hash tables (Dict). isequal(x,y) must imply that hash(x) == hash(y).

Thank you @anon94023334, is this documented somewhere? I wouldn’t find it myself by just looking at unique’s documentation.

It’s referenced in the isequal docstring:

isequal is the comparison function used by hash tables (Dict). isequal(x,y)
must imply that hash(x) == hash(y).
This typically means that if you define your own == function then you must
define a corresponding hash (and vice versa). Collections typically
implement isequal by calling isequal recursively on all contents.

Though, interestingly enough, it’s not mentioned in the == docstring.

1 Like

See also: https://github.com/JuliaLang/julia/issues/12198. It’s a recognized problem.