# Possible issue with \`unique\` when overloading \`isequal\`

**URL:** <https://discourse.julialang.org/t/possible-issue-with-unique-when-overloading-isequal/53079>\
**Category:** General Usage\
**Tags:** question\
**Created:** [January 9, 2021, 9:47am UTC](https://discourse.julialang.org/t/possible-issue-with-unique-when-overloading-isequal/53079 "2021-01-09T09:47:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![maltezfaria](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/maltezfaria/32/7728_2.png) [@maltezfaria](https://discourse.julialang.org/u/maltezfaria)\
**Post date:** [January 9, 2021, 9:47am UTC](https://discourse.julialang.org/t/possible-issue-with-unique-when-overloading-isequal/53079/1 "2021-01-09T09:47:23Z")

</div>

I am trying to understand why calling `unique` in the following example returns a vector containing two elements which are _equal_ as per `isequal`:

```julia
struct Tag
    tag::Int
end

Base.:(==)(t1::Tag,t2::Tag) = abs(t1.tag) == abs(t2.tag)  

t1 = Tag(1); t2 = Tag(-1);
isequal(t1,t2) # true
v = unique([t1,t2]) # returns [t1,t2]

```

So it seems that `v` contains both `t1` and `t2`, but `isequal(t1,t2)` is `true`, which seems puzzling to me given the documentation of `unique`. Am I missing something?

---

<div class="post-metadata">

**Author:** ![bkamins](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bkamins/32/208538_2.png) [@bkamins](https://discourse.julialang.org/u/bkamins)\
**Post date:** [January 9, 2021, 10:06am UTC](https://discourse.julialang.org/t/possible-issue-with-unique-when-overloading-isequal/53079/2 "2021-01-09T10:06:44Z")

</div>

If you look at the docstring if `isequal` you read:

> This typically means that types for which a custom `==` or `isequal` method exists must  
> implement a corresponding `hash` method (and vice versa).

similarly in the docstring of `==` you can read:

> `isequal` falls back to `==`, so new methods of `==` will be used by the `Dict` type to compare keys. If your type will be used as a dictionary key, it should therefore also implement `hash`.

The conclusion is that you should have implemented `hash` method for your `Tag`, which can be done e.g. like this (with this implementation hash of `Tag` will be the same as hash of `abs` of `tag` field stored in it):

```julia
Base.hash(x::Tag, h::UInt) = hash(abs(x.tag), h)

```

And now you have:

```julia
julia> unique([t1,t2])
1-element Array{Tag,1}:
 Tag(1)

```

---

<div class="post-metadata">

**Author:** ![maltezfaria](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/maltezfaria/32/7728_2.png) [@maltezfaria](https://discourse.julialang.org/u/maltezfaria)\
**Post date:** [January 9, 2021, 10:19am UTC](https://discourse.julialang.org/t/possible-issue-with-unique-when-overloading-isequal/53079/3 "2021-01-09T10:19:04Z")

</div>

Thanks!
