I'm learning Scala by working the exercises from the book "Scala for the Impatient". One of the questions asks:
/**
* Q5: One can use lists to model trees that store values only in the leaves. For example, the list ((3, 8) 2 (5))
* describes the tree
* .
* . 2 .
* 3 8 5
*
* However, some of the list elements are numbers and others are lists. In Scala, you cannot have heterogeneous lists,
* so you have to use a `List[Any]`. Write a `leafSum` function to compute the sum of all elements in the leaves,
* using pattern matching to differentiate between numbers and lists.
*
*/
My code:
def leafSum(lst: List[Any]): Int = {
type Node = Tuple2[_, List[Any]]
type Leaf = Tuple2[Int, Int]
lst.foldLeft(0) {
case (_, elem): Node => leafSum(elem)
case (_, _): Leaf => _ + _
}
}
However, both case statements fail to compile with the following error. Why?
type mismatch; found : Unit required: Int
Edit:
I know I can use collect
instead but I'd like foldLeft
to do the sum and not having to do it myself.
lst.collect {
case node: List[Any] => leafSum2(node)
case leaf: Int => leaf
}.sum
Edit2: See my solution below.