Is this a good approach?
let blob = Text.encodeUtf8(debug_show custom_object);
the reason i want to do this is because i want to use the Blob.compare
in the RBTree.mo
Is this a good approach?
let blob = Text.encodeUtf8(debug_show custom_object);
the reason i want to do this is because i want to use the Blob.compare
in the RBTree.mo
Almost certainly not, I’d say. If you want to use custom objects as keys, you are better off defining your own comparison function on the type of custom objects.
For example, if it was a record of comparable fields, then you might use a lexicographic ordering on those fields.
Alternatively, if every object has a unique, comparable id, then you could use the id as the basis for comparison.
.
hi again
do you recommend me if i use to_candid(transfer_arg)
(just found this) and Blob.compare
to look for duplicate transfer argument?
or is it better to use my custom function? it’s very long tho since i have to compare every property on the arguments
thank you
sorry, forgot to tag ur name @claudio
Yes, I think that’s generally the right pattern, though you can probably simplify your code by not creating those account blobs and just comparing the fields of a and b directly.
This issue is related utilities for tuple comparisons · Issue #602 · dfinity/motoko-base · GitHub and might inspire you.
Here’s a nice pattern you might be able to adopt:
For variants define a function tag that maps each variant to a distinct integer.
For the comparison, write a switch that compares values with equal variants and add a final case that only compares the integer tags of distinct variants. Like so:
type V = { #A : {aa:Int; ab: Nat};
#B : {ba:Int; bb: Nat};
#C : {ca:Int; cb: Nat};
};
// map a variant to an integer tag
func tag(v : V) : Int {
switch v {
case (#A _) 0;
case (#B _) 1;
case (#C _) 2;
}
};
func compare(v1 : V, v2 : V) : Order.Order {
switch (v1, v2) {
// equal variants
case (#A a1, #A a2) {
switch (Int.compare(a1.aa, a2.aa)) {
case(#equal) Nat.compare(a1.ab, a2.ab);
case other other;
}
};
case (#B b1, #B b2) {
switch (Int.compare(b1.ba, b2.ba)) {
case (#equal) Nat.compare(b1.bb, b2.bb);
case other other;
}
};
case (#C c1, #C c2) {
switch (Int.compare(c1.ca, c2.ca)) {
case (#equal) Nat.compare(c2.cb, c2.cb);
case other other;
}
};
// distinct variants, compare by tag
case (v1, v2) {
Int.compare(tag(v1),tag(v2))
}
}
}