Created
June 29, 2011 13:53
-
-
Save jrudolph/1053876 to your computer and use it in GitHub Desktop.
Custom Orderings
This file contains hidden or 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
sealed abstract class Bound[+T] { val value : T } | |
case class Closed[T : Ordering](value : T) extends Bound[T] | |
case class Opened[T : Ordering](value : T) extends Bound[T] | |
object Bound { | |
implicit def ordering[T: Ordering]: Ordering[Bound[T]] = Ordering.by((_: Bound[T]).value) | |
} | |
object BoundDemo { | |
def main(args : Array[String]) : Unit = { | |
val order = implicitly[Ordering[Bound[Int]]] | |
import order._ | |
// todo : Create an ordering on `Bound[T]` | |
assert((Closed(1) < Closed(10)) == true) | |
assert((Closed(10) > Opened(10)) == true) | |
def optionOrder[X: Ordering] = Ordering.by( (_: Option[X]) match { | |
case Some(_) => 1 | |
case None => 0 | |
}) | |
val bOptionOrder = optionOrder[Bound[Int]] | |
import bOptionOrder._ | |
// todo : Create an ordering on `Option[Bound[T]]` | |
assert((Some(Closed(1)) < Some(Closed(10))) == true) | |
assert((Some(Closed(10)) > Some(Opened(10))) == true) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment