Hello,
I would like to sort a list of key-element pairs, using predsort/3. I have defined a custom comparator that I pass to predsort/3; but in the resulting list, only the first element of the “equal” elements is retained; the others are dismissed.
This is a list that I want to sort according to the keys which are floating point numbers:
List = [4.001512214151045-[a,m],4.0-[b,m],3.9962607522532854-[c,m],3.996210705155572-[d,m],7.996561761157103-[a,c],2.4278591392418134-[c,e],5.568707210834485-[a,e],7.35185010728592-[b,d],3.6017356926904003-[d,e],3.7501199980800615-[b,e],4.459831835394693-[b,c],2.2271281956816043-[c,n12],2.2327113561766105-[b,n12],5.2559014450425146-[n11,n12],2.232576986354558-[e,n12],3.0233259830855155-[e,n11],6.635209115016647-[a,d],1.9580091930325554-[d,n11],4.6772000171042505-[a,n11],6.7180428697649734-[a,b],4.346147719532781-[c,d]]
This is the call to the sorting routine:
predsort(compare_with_tolerance, List, Sorted).
This is the sorted list:
Sorted = [2.4278591392418134-[c,e],3.0233259830855155-[e,n11],4.001512214151045-[a,m],5.568707210834485-[a,e],6.635209115016647-[a,d],7.35185010728592-[b,d],7.996561761157103-[a,c]]
This is the custom comparator which basically considers keys as equal as long as they do not differ from each other by more than a given threshold.
compare_with_tolerance(=, Key1-_, Key2-_):-
Tolerance = 0.5,
Diff is abs(Key1-Key2),
Diff =< Tolerance.
compare_with_tolerance(<, Key1-_, Key2-_):-
Tolerance = 0.5,
Diff1 is Key1-Key2,
Diff is abs(Diff1),
Diff > Tolerance,
Diff1 < 0.
compare_with_tolerance(>, Key1-_, Key2-_):-
Tolerance = 0.5,
Diff1 is Key1-Key2,
Diff is abs(Diff1),
Diff > Tolerance,
Diff1 > 0.
How do I make the predsort/3 retain all elements with “tolerably-equal” keys?
Thanks.