Skip to content

Instantly share code, notes, and snippets.

@jrudolph
Created June 29, 2011 13:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrudolph/1053876 to your computer and use it in GitHub Desktop.
Save jrudolph/1053876 to your computer and use it in GitHub Desktop.
Custom Orderings
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