Functional style early exit from depth-first recursion
I have a question about writing recursive algorithms in a functional style. I will use Scala for my example here, but the question applies to any functional language. I am doing a depth-first enumeration of an n -ary tree where each node has a label and a variable number of children. Here is a simple implementation that prints the labels of the leaf nodes. case class Node[T](label:T, ns:Node[T]*) def dfs[T](r:Node[T]):Seq[T] = { if (r.ns.isEmpty) Seq(r.label) else for (n<-r.ns;c<-dfs(n)) yield c } val r = Node('a, Node('b, Node('d), Node('e, Node('f))), Node('c)) dfs(r) // returns Seq[Symbol]