9

Given the following definition for a (not binary) tree:

sealed trait Tree[+A]
case class Node[A](value: A, children: List[Node[A]]) extends Tree[A]
object Tree {...}

I have written the following fold method:

def fold[A, B](t: Node[A])(f: A ⇒ B)(g: (B, List[B]) ⇒ B): B =
  g(f(t.value), t.children map (fold(_)(f)(g)))

that can be nicely used for (among other things) this map method:

def map[A, B](t: Node[A])(f: A ⇒ B): Node[B] =
  fold(t)(x ⇒ Node(f(x), List()))((x, y) ⇒ Node(x.value, y))

Question: can someone help me on how to write a tail recursive version of the above fold?

1 Answer 1

7

I believe you need a stack to do such a traversal, just as in imperative programming, there would be no natural way to write that without a recursive method. Of course, you can always manage the stack yourself, which moves it into the heap, and prevents stack overflows. Here is an example :

sealed trait Tree[+A]
case class Node[+A](value: A, children: List[Node[A]]) extends Tree[A]

case class StackFrame[+A,+B](
  value: A, 
  computedChildren: List[B], 
  remainingChildren: List[Node[A]])

def fold[A,B](t: Node[A])(f: A => B)(g: (B, List[B]) => B) : B = {

  def go(stack: List[StackFrame[A,B]]) : B = stack match {
    case StackFrame(v, cs, Nil) :: tail => 
      val folded = g(f(v), cs.reverse)
      tail match {
        case Nil => folded
        case StackFrame(vUp, csUp, remUp) :: rest => 
          go(StackFrame(vUp, folded::csUp, remUp)::rest)
      }
    case StackFrame(v, cs, nextChild :: others) :: tail =>
      go(
        StackFrame(nextChild.value, Nil, nextChild.children) ::
        StackFrame(v, cs, others) :: 
        tail)
    case Nil => sys.error("Should not go there")
  }

  go(StackFrame(t.value, Nil,  t.children) :: Nil)    
}

Note: I made Node covariant, not strictly necessary, but if it is not, you will need to be explicit in the type of a few Nil (e.g replace by List[X]()) in some place.

go it clearly tail recursive, but just because it manages the stack itself.

You may find a more principled and systematic technique (but not easy to grasp at first) based on continuations and trampolines, in this nice blog post.

4
  • Very clear (and effective), I also ventured into the blog post and related paper. Fascinating but difficult, accumulator on steroids... So I am not underestimating the issue, but let me say that from the "user" stand point it would be a dream to write a non-tail recursive one-liner and let the compiler find the best solution for optimization. Mar 6, 2015 at 10:41
  • The code can be slightly optimized substituting cs to cs.reverse and csUp :+ folded to folded :: csUp Mar 6, 2015 at 19:04
  • Isn't csUp :+ folded O(n)? Mar 6, 2015 at 19:54
  • Also a minor note, the canonical fold for your structure would be fold(Node[A])((A, List[B] => B) instead of your variant with two functions. There sonly one shape, so fold needs only one function. You will notice you can easily express your signature from this one, but not the other way round. Mar 6, 2015 at 19:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.