Scala Graph Cycle Detection Algo 'return' needed?

前端 未结 5 1092
你的背包
你的背包 2020-12-18 12:35

I have implemented a small cycle detection algorithm for a DAG in Scala. The \'return\' bothers me - I\'d like to have a version without the return...possible?



        
5条回答
  •  没有蜡笔的小新
    2020-12-18 13:08

    Yes, by using '.find' instead of '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()
      }
    }
    

提交回复
热议问题