gpt4 book ai didi

需要Scala Graph Cycle Detection Algo 'return'吗?

转载 作者:行者123 更新时间:2023-12-01 09:36:12 25 4
gpt4 key购买 nike

我在 Scala 中为 DAG 实现了一个小循环检测算法。'return' 困扰着我 - 我想要一个没有 return 的版本...可能吗?

  def isCyclic() : Boolean = {
lock.readLock().lock()
try {
nodes.foreach(node => node.marker = 1)
nodes.foreach(node => {if (1 == node.marker && visit(node)) return true})
} finally {
lock.readLock().unlock()
}
false
}

private def visit(node: MyNode): Boolean = {
node.marker = 3

val nodeId = node.id
val children = vertexMap.getChildren(nodeId).toList.map(nodeId => id2nodeMap(nodeId))
children.foreach(child => {
if (3 == child.marker || (1 == child.marker && visit(child))) return true
})

node.marker = 2

false
}

最佳答案

是的,使用 '.find' 而不是 'foreach' + 'return':

http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Seq

def isCyclic() : Boolean = {
def visit(node: MyNode): Boolean = {
node.marker = 3

val nodeId = node.id
val children = vertexMap.getChildren(nodeId).toList.map(nodeId => id2nodeMap(nodeId))
val found = children.exists(child => (3 == child.marker || (1 == child.marker && visit(child))))

node.marker = 2

found
}

lock.readLock().lock()
try {
nodes.foreach(node => node.marker = 1)
nodes.exists(node => node.marker && visit(node))
} finally {
lock.readLock().unlock()
}
}

关于需要Scala Graph Cycle Detection Algo 'return'吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7400959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com