O'Reilly logo

Learning Functional Data Structures and Algorithms by Raju Kumar Mishra, Atul Khot

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Cycle detection

What if we introduce a cycle? For example, refer to the cycle shown here:

Cycle detection

If you invoke the topsort method with this graph as an argument, it will never be completed:

scala> topsort(("dinner", "movie") :: grwork) 
java.lang.StackOverflowError 
...  

The fix is to remember that x is already seen, going to precede, so processing x again is a cycle. We just abort the execution in this case:

scala> def topsortWithCycle(g: List[(String, String)]) = { | def sort(nodes: List[String], path: List[String], visited: List[String]): | List[String] = nodes match { | case Nil => visited | case x :: xs if path.contains(x) => | throw new RuntimeException("Cycle ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required