Skip to content

Instantly share code, notes, and snippets.

@sgalles
Last active August 29, 2015 14:01
Show Gist options
  • Save sgalles/e5e8cfe63f4e1a6debf5 to your computer and use it in GitHub Desktop.
Save sgalles/e5e8cfe63f4e1a6debf5 to your computer and use it in GitHub Desktop.
"Create a comparator from an Iterable of Comparators"
shared class Comparing<Element>({Comparison(Element,Element)+} comparators){
alias Comparator => Comparison(Element,Element);
Comparator accumulating(Comparator partial, Comparator elem) {
Comparison newPartial(Element x, Element y){
value comparison = partial(x,y);
return comparison != equal then comparison else elem(x,y);
}
return newPartial;
}
shared Comparison(Element,Element) comparator = comparators.reduce(accumulating);
}
"Test it with a Person class"
class Person(shared String firstName, shared String lastName)
satisfies Comparable<Person>{
value comparator = Comparing{
byIncreasing(Person.lastName),
byIncreasing(Person.firstName)
}.comparator;
shared actual Comparison compare(Person other) => comparator(this,other);
}
shared void run() {
assert(Person("Bob","B") > Person("Henry","A"));
assert(Person("Bob","A") < Person("Henry","A"));
assert(Person("Bob","A") <=> Person("Bob","A") == equal);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment