Parameter -> equal : (X, X) in Buffer Documentation

Hello, sorry for this probably easy question but i can’t find the solution.

I add some Principals in a Buffer and I would like to remove duplicates Principals… There is many way to do, but Buffer methods always need the equal : (X, X) parameter… And I don’t know what is that and I didn’t easily find examples.

let buff : Buffer.Buffer<Principal> = Buffer.Buffer(10);
let principal1 = "xxxx-xxxx-..." 
let principal2 = "xxxx-xxxx-..." 

if( Buffer.contains(buff, principal1, ???) == false) // check if the principal is in the buffer
buff.add(principal1); //add if it's not

How can I properly use these methods please ? Could you give an easy example like this one ?

The type signature for equal is (X, X) -> Bool which means it is a function that takes 2 arguments of type X and returns a Bool.

In this case X is Principal so you can use Principal.equal:

If you never want duplicates you could consider using a Set data structure instead. I could only find this implementation:

1 Like

Thank you for this answer. This is was I tried to use : Principal.equal, as I used it to instanciate my Hashmaps, so, the problem is not from there…

Ok, I found immediately so, I had just forget to put var x = before my method :
var x = Buffer.contains(buff, q2.answers[i].principal, Principal.equal);

Thank you also for the explanation about Set, it seems to be what I was looking for !

I’m also unable to use this… I understand a little better these methods than before… But not perfectly yet.

I tried :

I get the error :

I don’t really understand why it expect Nat32 type instead of Hash type like it’s written in the prototype.

The argument xh has the type Hash. If we follow the imports we can see that that’s a type alias for Nat32:

You’re providing Hash.hash, which is a function that takes a Nat and returns a Hash:

Instead, you probably want to provide the equivalent of Principal.hash(q2.answers[i].principal) for that argument.

Evginey’s hashmap has a set implementation: GitHub - ZhenyaUsenko/motoko-hash-map: Stable hash maps for Motoko

Thanks :pray: :sparkles: very much