2

I am playing around with Scala and I am starting from some simple examples such as implementing binary trees. Having prior knowledge of functional programming (OCaml, F#) I was trying to replicate the common approach of using continuations in order to make a binary tree traversal tail-recursive. I am reading as much as I can about Scala's Delimited Continuations, but I have not been able to make it work.

You can read an OCaml implementation of this behaviour from this StackOverflow question

I followed the examples in this Introduction to Programming with Shift and Reset, but I am always getting type errors and the modifications I made to try making it work, gave correct results, but without making the function tail recursive.

Here's my implementation

abstract class IntTree
case object EmptyTree extends IntTree
case class Node( value : Int, left : IntTree, right : IntTree) extends IntTree

abstract class Result
case object Done extends Result
case class Next( n:Int, f : ( Unit => Result ) ) extends Result

def Sum(tree: IntTree): Int = {
  def walk( t : IntTree) : Unit = t match {
    case EmptyTree => ()
    case Node(v, left, right) => {
      walk(left)
      reset {
        shift { k: (Unit => Result) => Next(v, k) }
        walk(right)
      }
    }
  }
  def start( t : IntTree) = { walk(t); Done }
  def sumResult( ls : Result, acc : Int) : Int = ls match {
    case Done => acc
    case Next(value, k) => {
      sumResult(k(), acc + value)
    }
  }


  sumResult( start(tree), 0 )
}

I am also wondering if Delimited Continuations are the right tool for this job. I know this problem can be solved efficiently passing an explicit stack, but I would like to understand how to use cps in Scala.

Community
  • 1
  • 1
Fr.Usai
  • 384
  • 2
  • 17
  • Continued support for delimited continuations is iffy, given that they (as currently designed) introduce a lot of complexity without enabling very much that you can't do manually with a little extra syntax. So I'm not sure understanding how to use CPS is a valuable skill to have (though it can still be a good general experience in how to think through certain kinds of things). Also, you should search _Scala trampoline_ for this particular application! (Not CPS at all.) – Rex Kerr May 31 '16 at 18:18
  • Thank you. So it is something halfway being discontinued and not the right tool for the job. It was more or less an experiment of using the cps approach that I already knew from other languages to solve this kind of problem. I would take a look at trampolines ( they will be supported in the future? as far as you know ). I am however interested in seeing a solution to this puzzle :) – Fr.Usai May 31 '16 at 19:38
  • Trampolines don't take any special machinery to work; they're just using basic Scala features to have an implicit heap-based stack (effectively). – Rex Kerr Jun 01 '16 at 03:12

0 Answers0