如何在Scala中编写以下Java代码?目的是遍历树结构并返回与谓词匹配的第一个元素。
public class MyObject {
private String id;
private List<MyObject> children;
public MyObject findById(String otherId) {
if (this.id.equals(otherId)) {
return this;
} else {
for (MyObject child : children) {
MyObject found = child.findById(otherId);
if (found != null) {
return found;
}
}
return null;
}
}
}
scala看起来像这样,但我不知道在else子句中放什么。
class MyObject(id: String, children: List[MyObject]) {
def findById(otherId: String): Option[MyObject] = {
if (this.id == otherId) {
Some(this)
} else {
//What goes here?
}
}
}
答案 0 :(得分:4)
您应该实施tail recursive搜索,这样您就不会获得stack overflow:
class MyObject(val id: String, val children: List[MyObject]) {
def findById(otherId: String): Option[MyObject] = {
@tailrec
def recurseOverChildren(list: List[MyObject]): Option[MyObject] = {
list match {
case Nil => None
case head :: tail =>
if(head.id == otherId) Some(head)
else recurseOverChildren(tail ++ head.children)
}
}
recurseOverChildren(List(this))
}
}
递归很简单,我们只检查列表的head
是否是我们正在搜索的项目。如果不是,我们将它的子项添加到列表的末尾。如果列表为空,则该项不在树中。我们使用包含一个元素的列表初始化搜索:调用函数的元素。
这将是breadth first search,如果您想要depth first search,则将孩子们添加到列表前面,而不是最后。