1

假设我有一个Tree包含 2 个成员对象的对象,right并且left.

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

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

2 回答 2

4

您的示例不是有效的 Scala,但匹配 Tree 的惯用方法是使用提取器(查找它)。如果Tree是案例课程,您可以免费获得这个。假设是,你可以写

tree match {
  case Tree(Nil, Nil) => acc
  case Tree(Nil, x) => ...
  case Tree(x, Nil) => ...
  case Tree(x, y) => ...
}
于 2013-08-17T02:47:52.383 回答
3

或者,如果您希望按Tree原样使用非案例类,那么您可以尝试 Luigi 解决方案的这种变体:

(tree.left, tree.right) match {
  case (Nil, Nil) => acc
  case (Nil, x) => ...
  case (x, Nil) => ...
  case (x, y) => ...
于 2013-08-17T03:08:49.910 回答