Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 带折叠的抽象类型的模式匹配_Scala_Pattern Matching_Scala Macros - Fatal编程技术网

Scala 带折叠的抽象类型的模式匹配

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

这是对一项远未完成的计划的后续行动。随后的所有代码都在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 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