title: Creating sum tree of binary tree scala
body: <p>For a homework assignment I wrote some scala code in which I have the following classes and object (used for modeling a binary tree):</p>
  
  <pre><code>object Tree {
    def fold[B](t: Tree, e: B, n: (Int, B, B) =&gt; B): B = t match {
      case Node(value, l, r) =&gt; n(value,fold(l,e,n),fold(r,e,n))
      case _ =&gt; e
    }
    def sumTree(t: Tree): Tree = 
      fold(t, Nil(), (a, b: Tree, c: Tree) =&gt; {
        val left = b match {
          case Node(value, _, _) =&gt; value
          case _ =&gt; 0
        }
        val right = c match {
          case Node(value, _, _) =&gt; value
          case _ =&gt; 0
        }
        Node(a+left+right,b,c)
      })
  }
  
  abstract case class Tree
  case class Node(value: Int, left: Tree, right: Tree) extends Tree
  case class Nil extends Tree
  </code></pre>
  
  <p>My question is about the <code>sumTree</code> function which creates a new tree where the nodes have values equal to the sum of the values of its children plus it's own value.</p>
  
  <p>I find it rather ugly looking and I wonder if there is a better way to do this. If I use recursion which works top-down this would be easier, but I could not come up with such a function.</p>
  
  <p>I have to implement the <code>fold</code> function, with a signature as in the code, to calculate <code>sumTree</code></p>
  
  <p>I got the feeling this can be implemented in a better way, maybe you have suggestions?</p>