0

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

所以它看起来像这样:

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某种程度上遇到了麻烦。任何想法如何在这里工作?

我也不是 100% 满意将树叶和树枝包裹在Either. 这是必要的,因为当我试图定义一个超类型并弄清楚如何在实现中正确地子类型时,这些东西失控了LeafLikeBranchLike并且模式匹配也失败了,因为我不知道如何得到正确的提取器。所以也许使用Either不是一个坏主意?

4

1 回答 1

0

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

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

这使它编译。只是如果它即将倒塌,我不太有动力继续建造这个结构:-(

于 2013-10-30T10:19:24.773 回答