Skip to content

Instantly share code, notes, and snippets.

@kenbot
Created July 3, 2015 00:29
Show Gist options
  • Save kenbot/1c37f10cd2ac8de2e988 to your computer and use it in GitHub Desktop.
Save kenbot/1c37f10cd2ac8de2e988 to your computer and use it in GitHub Desktop.
Interval
import scala.math.Ordering
sealed trait Interval[A] {
def intersect(that: Interval[A])(implicit order: Ordering[A]): Interval[A] = (this, that) match {
case (Nonempty(s1, e1), Nonempty(s2, e2)) if (order.gteq(e2,s1)) && (order.gteq(e1,s2)) =>
val start = order.max(s1, s2)
val end = order.min(e1, e2)
Nonempty(start, end)
case _ => Empty()
}
}
final case class Nonempty[A](start: A, end: A) extends Interval[A]
final case class Empty[A]() extends Interval[A]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment