Home > Blockchain >  How recursion in scala tree((sealed trait)
How recursion in scala tree((sealed trait)

Time:04-15

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)

CodePudding user response:

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:

def sum_tree(t: Tree[Int]): Int = t match
  case Leaf(elem)       => elem
  case Node(elem, l, r) => elem   sum_tree(l)   sum_tree(l)
  • Related