Skip to content

Instantly share code, notes, and snippets.

@ThiporKong
Last active October 5, 2020 21:35
Show Gist options
  • Save ThiporKong/4399695 to your computer and use it in GitHub Desktop.
Save ThiporKong/4399695 to your computer and use it in GitHub Desktop.
Topological sorting: simple implementation in pure Scala
def tsort[A](edges: Traversable[(A, A)]): Iterable[A] = {
@tailrec
def tsort(toPreds: Map[A, Set[A]], done: Iterable[A]): Iterable[A] = {
val (noPreds, hasPreds) = toPreds.partition { _._2.isEmpty }
if (noPreds.isEmpty) {
if (hasPreds.isEmpty) done else sys.error(hasPreds.toString)
} else {
val found = noPreds.map { _._1 }
tsort(hasPreds.mapValues { _ -- found }, done ++ found)
}
}
val toPred = edges.foldLeft(Map[A, Set[A]]()) { (acc, e) =>
acc + (e._1 -> acc.getOrElse(e._1, Set())) + (e._2 -> (acc.getOrElse(e._2, Set()) + e._1))
}
tsort(toPred, Seq())
}
println(tsort(Seq((1, 2), (2, 4), (3, 4), (3, 2), (1,3))))
@informarte
Copy link

Would you mind to make this nice piece of code available under some permissive licence (like MIT or BSD) such that it can be used in open-source projects?

@jessitron
Copy link

this was useful, thanks. +1 to @infomarte's comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment