我正在通过“Scala for the Impatient”一书中的练习来学习Scala。其中一个问题是:
/**
* 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
EDIT2 : 请参阅下面的解决方案。
答案 0 :(得分:2)
模式匹配需要一些调整。如果有效,请告诉我。
if ((amount >= 0) && (amount <= 2)) System.out.println(array[amount]);
答案 1 :(得分:0)
这很有效。 @marios的回答让我走上了正确的道路,尽管他的实现有一个错误但没有用。
def leafSum(lst: List[Any]): Int = {
lst.foldLeft(0) {
case (sum, node: List[_]) => sum + leafSum(node)
case (sum, leaf: Int) => sum + leaf
}
}