2013-08-17 49 views
1

比方说,我有一个Tree对象,其中包含2个成员对象rightleft检查会员是否为

检查tree的“右”和“左”字段是否为零的常用/正确方法是什么?

def count(tree: Tree, acc: Int) : Int = tree match { 

    case tree .right != Nil && tree .left != Nil => countLeftAndRight(...) 
    case tree .right != Nil => countOnlyRight(...) 
    case tree .left != Nil => countOnlyLeft(...) 
    _    => acc 
} 
+0

什么是'x'?您的匹配块似乎不合法。 – pedrofurla

+0

对不起 - 我更新为'tree',而不是'x' –

回答

4

您的示例不是有效的Scala,但与Tree匹配的惯用方式是使用提取器(查找它)。如果Tree是个案例类别,您可以免费获得此信息。假如是这样,你可以写

tree match { 
    case Tree(Nil, Nil) => acc 
    case Tree(Nil, x) => ... 
    case Tree(x, Nil) => ... 
    case Tree(x, y) => ... 
} 
+0

case语句中的'x'和'y'是否指示'tree'对象中的任何非'Nil'值? –

+1

它们是将被绑定到提取器返回值的变量。 (重要的是,它们以小写字母开头。)可以包含值'Nil',这就是为什么我们先匹配'Nil',所以下面的情况是非零。 –

3

或者,如果你愿意与你Tree不区分一流工作原样,那么你可以尝试Luigi的解决方案的这种变化:

(tree.left, tree.right) match { 
    case (Nil, Nil) => acc 
    case (Nil, x) => ... 
    case (x, Nil) => ... 
    case (x, y) => ...