Reputation: 19
when I programming task in scala I crashed the problem
the error code is missing parameter type for expanded function.
Expected type was: Int def sum_tree(t : Tree[Int]): int ={
sealed trait Tree[Int]
case class Leaf[Int](elem: Int) extends Tree[Int]
case class Node[Int](elem: Int, left: Tree[Int], right: Tree[Int]) extends Tree[Int]
val tree = Node(7, Node(3, Leaf(1), Leaf(2)), Leaf(4))
def sum_tree(t : Tree[Int]): Int = {
//must use recursion call function.
case Leaf(elem) => elem
case Node(elem, l, r) => elem + sum_tree(l) + sum_tree( l )
case None => 0
}
println("** p6 **")
println(sum_tree(tree)
Upvotes: 1
Views: 87
Reputation: 143403
Your pattern matching is missing match
to be a valid match expression. Also note that t
is Tree
and there is None
declared which implements it so last case clause is invalid; and you were calling sum_tree(l)
twice when the second one should be sum_tree(r)
def sum_tree(t: Tree[Int]): Int = t match
case Leaf(elem) => elem
case Node(elem, l, r) => elem + sum_tree(l) + sum_tree(r)
Upvotes: 1