2017-10-08 51 views
-2

我试图重构一些代码并使用更高阶的函数。但由于某种原因,当我将该函数作为参数传递给它自己的函数时。我收到错误无法解析引用“权重”与这样的签名。在斯卡拉:如何递归地将函数作为参数传递给它自己的函数调用

这里是我的代码:

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

'weight'后面的括号看起来不对(特别是右括号后面的逗号)。你可能是指'走路(树,体重,_ ++ _)'? – sepp2k

+0

也只是看着它:我看到你编辑了代码,它没有解决这个问题? – Ossip

+0

'weight'返回'Int',但你说'_ ++ _'。在'Int's上没有'++'操作。我对吗? –

回答

0

我猜走法应该返回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) 
} 
相关问题