Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regular shaped tree fold left scala implementation

I'm trying to implement a tail-recursive foldLeft function for a regular shaped tree. The exercise comes from the book, "The Science of Functional Programming," in exercise 3.3.5.3.

Until now, I was able to do the exercises but I don't know what I'm missing in this one.

There's is a definition for the regular shaped tree:

sealed trait RTree[A]
final case class Leaf[A](x: A) extends RTree[A]
final case class Branch[A](xs: RTree[(A,A)]) extends RTree[A]

The method signature and expected result:

@tailrec
def foldLeft[A,R](t: RTree[A])(init: R)(f: (R,A)=>R): R= ???

foldLeft(Branch(Branch(Leaf(((1,2),(3,4))))))(0)(_+_)
//10

The biggest problem so far is that I don't know how to match and access the element inside the case class of Branch. I can only match the Leaf and Branch (and not the leaf's inside a branch) and because of that the recursion has no end.

like image 484
Sebastian Zapata Avatar asked Dec 20 '19 18:12

Sebastian Zapata


1 Answers

Not sure if this helps, but for now I have only NON tail-recursive implementation.

def foldLeft[A, R](t: RTree[A])(init: R)(f: (R, A) => R): R = {
      t match {
        case Leaf(value) => f(init, value)
        case Branch(tree) =>
          foldLeft(tree)(init) {
            case (result, (left, right)) => f(f(result, left), right)
          }
      }
    }

UPDATE: As was said in comments section to this answer this is actually tail rec implementation, excuse me, for confusing you.

like image 92
Ivan Kurchenko Avatar answered Nov 10 '22 00:11

Ivan Kurchenko