Scala 检查成员是否为零
假设我有一个Scala 检查成员是否为零,scala,Scala,假设我有一个树对象,它有两个成员对象,右和左 检查树的“right”和“left”字段是否为零的惯用/正确方法是什么 def count(tree: Tree, acc: Int) : Int = tree match { case tree .right != Nil && tree .left != Nil => countLeftAndRight(...) case tree .right != Nil => countOnlyRight(...)
树
对象,它有两个成员对象,右
和左
检查树的“right”和“left”字段是否为零的惯用/正确方法是什么
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
}
您的示例不是有效的Scala,但匹配树的惯用方法是使用提取器(查找)。如果Tree
是一个case类,那么您可以免费获得它。假设是,你可以写
tree match {
case Tree(Nil, Nil) => acc
case Tree(Nil, x) => ...
case Tree(x, Nil) => ...
case Tree(x, y) => ...
}
您的示例不是有效的Scala,但匹配树的惯用方法是使用提取器(查找)。如果Tree
是一个case类,那么您可以免费获得它。假设是,你可以写
tree match {
case Tree(Nil, Nil) => acc
case Tree(Nil, x) => ...
case Tree(x, Nil) => ...
case Tree(x, y) => ...
}
或者,如果您希望按原样使用非case类树
,则可以尝试Luigi解决方案的以下变体:
(tree.left, tree.right) match {
case (Nil, Nil) => acc
case (Nil, x) => ...
case (x, Nil) => ...
case (x, y) => ...
或者,如果您希望按原样使用非case类树
,则可以尝试Luigi解决方案的以下变体:
(tree.left, tree.right) match {
case (Nil, Nil) => acc
case (Nil, x) => ...
case (x, Nil) => ...
case (x, y) => ...
什么是x
?您的匹配块似乎无效。抱歉-我更新为树
,而不是x
什么是x
?您的匹配块似乎无效。抱歉-我更新为树
,而不是x
,case语句中的x
和y
是否指示树
对象中的任何非Nil
值?它们是将绑定到提取器返回的值的变量。(重要的是它们以小写字母开头。)这可以包括值Nil
,这就是为什么我们首先匹配Nil
,因此,以下情况是非Nil。case语句中的x
和y
是否表示树
对象中的任何非Nil
值?它们是绑定到提取器返回的值的变量。(重要的是它们以小写字母开头。)这可以包括值Nil
,这就是为什么我们首先匹配Nil
,因此以下情况是非Nil。