2012-10-23 115 views
0

我想要这个匹配两个案例类的比较函数,但它有点冗长。在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 sortCodeTreeFun(x: CodeTree, y: CodeTree) = { 
    (x, y) match { 
     case (x1: Leaf, y1: Leaf) => true 
     case (x1: Fork, y1: Leaf) => x1.weight < y1.weight 
     case (x1: Leaf, y1: Fork) => x1.weight < y1.weight 
     case (x1: Fork, y1: Fork) => x1.weight < y1.weight 
    } 
    } 

我试图修改码树的构造是:

abstract class CodeTree(weight: Int) 

所以,我可以直接比较X和Y,但是编译器说:

“没有足够的论据构造码树:(weight:Int)patmat.Huffman.CodeTree“

有没有另一种方法缩短sortCodeTreeFun方法?

+5

这是从FP Scala的功课在线课程 – smk

+0

纯违反荣誉规章4“在斯卡拉功能编程” 当然导体“我不会试图不诚实地改进我的代码....“ –

+0

我已经完成了任务并获得了10/10。在尝试提高对Scala语言的理解时,看不到任何不光彩的东西。 – Zotov

回答

2

你可以简单地说:

def sortCodeTreeFun(x: CodeTree, y: CodeTree) = { 
    (x, y) match { 
    case (_: Leaf, _: Leaf)   => true 
    case (x1: CodeTree, y1: CodeTree) => x1.weight < y1.weight 
    } 
} 

,并定义抽象类码树为

abstract class CodeTree { 
    def weight: Int 
} 

的原因错误是,当你扩展该带一个参数的类,你需要提供参数。因此,对于

abstract class CodeTree(weight: Int) 

你需要把它延伸

case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree(weight) 

这就是你得到的错误是说:

"not enough arguments for constructor CodeTree: (weight: Int)" 

那是因为你没有提供所需参数扩展CodeTree时为weight

虽然这种方法的问题是重量不是CodeTree的成员,因此无法从CodeTree类型的实例访问。也就是说,如果你这样做:

scala> Fork(...).asInstanceOf[CodeTree].weight 
<console>:11: error: value weight is not a member of CodeTree 

所以,在你的模式匹配,你将无法做到x1.weight因为X1的类型是CodeTreeCodeTree没有一个weight

+0

太好了,谢谢!但是,请你解释我为什么会收到错误? – Zotov

+0

因为您在扩展CodeTree时没有提供权重。 –

+0

@维克多克拉格说什么。编辑包括错误的原因。虽然可能会有点啰嗦:)。 – rjsvaljean