在 Scala 中:如何递归地将函数作为参数传递给其自身中的函数调用



我正在尝试重构一些代码并使用高阶函数。 但出于某种原因,当我将函数作为参数传递给其自身中的函数时。我收到错误无法使用此类签名解析引用"权重"。

这是我的代码:

abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree  
def walk[T](t: CodeTree, op: CodeTree => T, cmb: (T,T) => T) = t match {
  case Fork(l,r,_,_) => cmb(op(l), op(r))
  case Leaf(_,x)     => x
}
def weight(tree: CodeTree): Int = walk[Int](tree, weight, _ ++ _)
def chars(tree: CodeTree): List[Char] = tree match {
  case Fork(l,r,x,_) => chars(l) ++ chars(r)
  case Leaf(x,_)     => List(x)
}

我想步行方法应该返回T++应该+,这是你想做的吗?

abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree  
def walk[T](t: CodeTree, op: CodeTree => T, cmb: (T,T) => T): T = t match {
  case Fork(l,r,_,_) => cmb(op(l), op(r))
  case t: Leaf     => op(t)
}
def weight(tree: CodeTree): Int = walk[Int](tree, weight, _ + _)
def chars(tree: CodeTree): List[Char] = tree match {
  case Fork(l,r,x,_) => chars(l) ++ chars(r)
  case Leaf(x,_)     => List(x)
}

最新更新