Back to questions
JuniorTheoryCommon
What does the program print (lines separated by spaces)?
fun main() {
val nums = listOf(2, 3, 4)
println(nums.fold(10) { acc, n -> acc + n })
println(nums.reduce { acc, n -> acc * n })
}19 24
- Expecting
reduceto start from0: it has no start value and begins with the first element,2, so the product is2 * 3 * 4. - Expecting
foldto use10only for an empty list: the running total always begins with the start value, so10is part of the sum.
- What happens to each of the two calls if
numsis an empty list? - How would you compute the same product with
foldinstead ofreduce?