Created
June 2, 2014 10:41
-
-
Save milessabin/88237c53916f8357b894 to your computer and use it in GitHub Desktop.
Dependent pattern matching in Scala or just a GADT?
This file contains 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
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