If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Friday, March 7, 2014

Ceylon: Range and Enumerable

/**
A quick look at the signature of Range reveals
class Range<Element>
extends Object() satisfies [Element+] & Cloneable<Range<Element>>
given Element satisfies Ordinal<Element> & Comparable<Element>
So in order to use a class in range notation we have to satisfy Ordinal & Comparable.
Let's get started and come up with an example :)
Oh yes... I used Enumerable which is a subtype of Ordinal.
**/
shared abstract class Priority(name, integerValue)
of low | middle | high | critical
satisfies Enumerable<Priority> & Comparable<Priority> {
shared String name;
shared actual Integer integerValue;
shared actual Comparison compare(Priority other) => integerValue <=> other.integerValue;
shared actual String string => name;
}
//ATTENTION !! You have to use the arrow notation for defining successor
//and predecessor, meaning it is lazy evaluated because otherwise
//you will run into a cyclic initialization error.
shared object low extends Priority("minor", 1) {
shared actual Priority predecessor => critical;
shared actual Priority successor => middle;
}
shared object middle extends Priority("middle", 2) {
shared actual Priority predecessor => low;
shared actual Priority successor => high;
}
shared object high extends Priority("high", 3) {
shared actual Priority predecessor => middle;
shared actual Priority successor => critical;
}
shared object critical extends Priority("critical", 4) {
shared actual Priority predecessor => high;
shared actual Priority successor => low;
}
/**
This prints
**************prios for range middle..critical
middle
high
critical
**************prios for range critical..middle
critical
high
middle
**************prios for range high..minor
high
middle
minor
**/
void range_demo() {
printPrios(middle..critical);
printPrios(critical..middle);
printPrios(high..low);
}
void printPrios(Range<Priority> prios) {
print("**************prios for range ``prios``");
for (prio in prios) {
print(prio);
}
}

No comments:

Post a Comment