Scala 使用模式匹配对树的叶子中的所有元素求和

Scala sum of all elements in the leaves of a tree using pattern matching

我正在通过书中的练习来学习 Scala "Scala for the Impatient"。其中一个问题问:

/**
   * 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.
   *
   */

我的代码:

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 => _ + _
  }
}

但是,两个 case 语句都无法编译并出现以下错误。为什么?

类型不匹配;发现:所需单位:Int

编辑: 我知道我可以使用 collect 代替,但我希望 foldLeft 求和而不必自己做。

lst.collect {
  case node: List[Any] => leafSum2(node)
  case leaf: Int => leaf
}.sum

编辑2: 请参阅下面我的解决方案。

模式匹配需要一些调整。让我知道这是否有效。

  // No need for the type aliases to be redefined on each function call
  type Node = Tuple2[_, List[Any]]
  type Leaf = Tuple2[Int, Int]

  def leafSum(lst: List[Any]): Int = {
     lst.foldLeft(0) {
       case (sum, x: List[_]) => sum + leafSum(x)
       case (a: Int, b: Int) => a + b
     }
  }

这行得通。 @marios 的回答让我走上了正确的道路,尽管他的实现有一个错误并且没有用。

def leafSum(lst: List[Any]): Int = {
  lst.foldLeft(0) {
    case (sum, node: List[_]) => sum + leafSum(node)
    case (sum, leaf: Int) => sum + leaf
  }
}