在Scala中:如何递归地将函数作为参数传递给它自己的主体

时间:2017-10-08 21:43:12

标签: scala

我正在尝试重构一些代码并使用更高阶的函数。但由于某种原因,我将函数作为参数传递给自己体内的函数。我收到错误无法使用此签名解析引用'weight'。

这是我的代码:

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)
}

1 个答案:

答案 0 :(得分:0)

我猜walk方法应该返回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)
}