Skip to content

Instantly share code, notes, and snippets.

@milessabin
Created June 2, 2014 10:41
Show Gist options
  • Save milessabin/88237c53916f8357b894 to your computer and use it in GitHub Desktop.
Save milessabin/88237c53916f8357b894 to your computer and use it in GitHub Desktop.
Dependent pattern matching in Scala or just a GADT?
trait Dep[T]
trait Pack[T] {
val dep: Dep[T]
val t: T
}
object Pack {
def apply[T](d: Dep[T], t0: T) =
new Pack[T] { val dep = d ; val t = t0 }
def unapply[T](p: Pack[T]): Option[(Dep[T], T)] = Some(p.dep, p.t)
}
object IntDep extends Dep[Int]
object StringDep extends Dep[String]
def depMatch[T](d: Dep[T], t: T): Option[(T, T)] =
Pack(d, t) match {
case Pack(IntDep, i) => Some((i, i*2)) // t refined to Int
case Pack(StringDep, s) => Some((s, s+"!")) // t refined to String
case _ => None
}
depMatch(IntDep, 23) // 46
depMatch(StringDep, "foo") // "foo!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment