Scala 带折叠的抽象类型的模式匹配
这是对一项远未完成的计划的后续行动。随后的所有代码都在Scala控制台中编译并正常运行 考虑以下抽象数据类型及其作为typeclass必须支持的操作:Scala 带折叠的抽象类型的模式匹配,scala,pattern-matching,scala-macros,Scala,Pattern Matching,Scala Macros,这是对一项远未完成的计划的后续行动。随后的所有代码都在Scala控制台中编译并正常运行 考虑以下抽象数据类型及其作为typeclass必须支持的操作: trait SIG { type XOrY type X <: XOrY type Y <: XOrY } trait SIGOps[Sig <: SIG] { def makeX(s: String): Sig#X def makeY(i: Int): Sig#Y // the disjunction
trait SIG {
type XOrY
type X <: XOrY
type Y <: XOrY
}
trait SIGOps[Sig <: SIG] {
def makeX(s: String): Sig#X
def makeY(i: Int): Sig#Y
// the disjunction is enforced with that fold
def fold[T](xy: Sig#XOrY)(isX: String => T, isY: Int => T): T
// the following is for convenience, as we want to mimick case classes
object X {
def apply(s: String): Sig#X = makeX(s)
def unapply(xy: Sig#XOrY): Option[String] = fold(xy)(s => Some(s), i => None)
}
object Y {
def apply(i: Int): Sig#Y = makeY(i)
def unapply(xy: Sig#XOrY): Option[Int] = fold(xy)(s => None, i => Some(i))
}
}
最后,这里是如何编写依赖于抽象签名的代码
class Example[Sig <: SIG](implicit ops: SIGOps[Sig]) {
import ops._
def main(args: Array[String]): Unit = {
val xy: Sig#XOrY = X("foo")
xy match {
case X(s) => println("X: "+s)
// Scala does not see that the pattern matching is not exhaustive if when I comment the following line
// case Y(i) => println("Y: "+i)
}
}
}
object ConcreteExample extends Example[EitherSig]
问题是:当模式匹配不是如上所述的穷举时,我如何教Scala识别
可能有,但我不知道怎么做。杰森·扎格给出:
[…]我们没有这个扩展点。只考虑密封的层次结构
特拉维斯·布朗(Travis Brown)写一个检查部分函数的匹配宏
,但当你有了折叠时,他认为这不值得麻烦
所以现在这个问题还没有真正的解决方案
class Example[Sig <: SIG](implicit ops: SIGOps[Sig]) {
import ops._
def main(args: Array[String]): Unit = {
val xy: Sig#XOrY = X("foo")
xy match {
case X(s) => println("X: "+s)
// Scala does not see that the pattern matching is not exhaustive if when I comment the following line
// case Y(i) => println("Y: "+i)
}
}
}
object ConcreteExample extends Example[EitherSig]
scala> ConcreteExample.main(Array())
X: foo