Last active
August 29, 2015 14:01
-
-
Save sgalles/e5e8cfe63f4e1a6debf5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"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