【发布时间】:2013-11-18 22:37:14
【问题描述】:
我有一个树形结构:
sealed trait Tree
case class Node(l: Tree, r: Tree) extends Tree
case class Leaf(n: Int) extends Tree
还有一个修改树的函数:
def scale(n: Int, tree: Tree): Tree = tree match {
case l: Leaf => Leaf(l.n * n)
case Node(l, r) => Node(scale(n, l), scale(n, r))
}
上述方法的签名应该是什么才能返回适当的 Tree 子类型,并使以下行编译?
scale(100, Leaf(1)).n // DOES NOT COMPILE
到目前为止我找到的最接近的答案是here,并谈到了F-Bounded Quantification。但是我找不到将其应用于递归结构(例如树)的方法!有什么想法吗?
【问题讨论】:
-
我不确定您所说的“适当的树子类型”是什么意思。我的猜测是创建
def scale(n: Int, tree: Tree): Either[Tree,Node]并将Leaf和Node值更改为Right(Leaf(...))和Left(Node(...))。使用这种方法,甚至可以消除模式匹配,因为参数中的也是一个。 -
我认为在编译时无法从输入参数中确定
scale的结果类型。但是为什么要麻烦,您可以在比例结果上使用模式匹配来获得 n,这是一种常见的做法。Either[Leaf, Node]不会带来任何新的东西,因为您将匹配左/右而不是这只是一个冗余代码。
标签: scala recursion type-systems