Scr*_*tch 1 functional-programming scala
说我有一个List. 我filter首先在某些条件下。现在我想将过滤后的数组中的初始值传递给foldLeft所有人,同时将两者链接在一起。有没有办法做到这一点?
例如:
scala> val numbers = List(5, 4, 8, 6, 2)
val numbers: List[Int] = List(5, 4, 8, 6, 2)
scala> numbers.filter(_ % 2 == 0).foldLeft(numbers(0)) { // this is obviously incorrect since numbers(0) is the value at index 0 of the original array not the filtered array
| (z, i) => z + i
| }
val res88: Int = 25
Run Code Online (Sandbox Code Playgroud)
您可以只对过滤结果进行模式匹配以获取列表的第一个元素 (head) 和其余元素 (tail):
val numbers = List(5, 4, 8, 6, 2)
val result = numbers.filter(_ % 2 == 0) match {
case head :: tail => tail.foldLeft(head) {
(z, i) => z + i
}
// here you need to handle the case, when after filtering there are no elements, in this case, I just return 0
case Nil => 0
}
Run Code Online (Sandbox Code Playgroud)
你也可以只使用reduce:
numbers.filter(_ % 100 == 0).reduce {
(z, i) => z + i
}
Run Code Online (Sandbox Code Playgroud)
但在过滤列表为空后,它会抛出异常。