解决令人讨厌的模式匹配器错误

时间:2013-10-30 10:14:32

标签: scala types pattern-matching

我正在定义一个通用的树结构,即可以扩展的树结构,例如,树枝和树叶包含其他值(例如,我需要添加名称字符串)。

所以它看起来像这样:

trait TreeNodes {
  val Node              = Either
  type Node[+B, +L]     = Either[B, L]
  val IsBranch          = Left
  type IsBranch[+B, +L] = Left[B, L]
  val IsLeaf            = Right
  type IsLeaf[+B, +L]   = Right[B, L]
}

object TreeLike extends TreeNodes {
  trait BranchLike[Elem, B, L] {
    type N = Node[B, L]

    def iterator: Iterator[N]
  }

  trait LeafLike[Elem] {
    def value: Elem
  }
}
trait TreeLike[Elem, Repr] {
  type Leaf   <: TreeLike.LeafLike[Elem]
  type Branch <: TreeLike.BranchLike[Elem, Branch, Leaf]

  def root: Branch
}

不幸的是,有一个模式匹配器错误:

def test[Elem, T <: TreeLike[Elem, T]](tree: T): Unit = {
  import TreeLike.{IsLeaf, IsBranch}

  def printLeaves(b: T#Branch): Unit = b.iterator.foreach {
    case IsLeaf(l)    => println(l.value)
    case IsBranch(c)  => printLeaves(c)
  }

  printLeaves(tree.root)
}

错误如下:

[error]         during phase: patmat
[error]      library version: version 2.10.3
[error]     compiler version: version 2.10.3
...
[error]    symbol definition: case val x1: b.N
[error]                  tpe: b.N
[error]        symbol owners: value x1
[error]       context owners: value x0$1 -> value $anonfun -> method printLeaves -> 
  method test -> object Voodoo -> package typerbug
...
[error] no-symbol does not have an owner

我怀疑patmat在某种程度上遇到了T#Branch的麻烦。任何想法如何在这里解决?

Either中包裹树叶和树枝我也不是很满意。这是必要的,因为当我试图定义一个超级类型的LeafLikeBranchLike并弄清楚如何在实现中正确地进行子类型时,这些东西已经失控了,模式匹配也完成了因为我没弄明白如何获得正确的提取器。所以也许使用Either并不是一个坏主意?

1 个答案:

答案 0 :(得分:0)

类型别名N是一个“问题”(WTF)。

  trait BranchLike[Elem, B, L] {
    def iterator: Iterator[Node[B, L]]
  }

这使它编译。只有当我即将崩溃时,我才不会继续建立这种结构: - (