// Created on savesnippets.com ยท https://savesnippets.com/toKUl2Bmc1btxX fun main() { val nums = listOf(1, 2, 3, 4, 5) // fold โ€” explicit initial value (handles empty input) val sum = nums.fold(0) { acc, n -> acc + n } val product = nums.fold(1) { acc, n -> acc * n } println("$sum $product") // 15 120 // Sum + count in a single pass with a Pair accumulator val (total, count) = nums.fold(0 to 0) { (s, c), n -> (s + n) to (c + 1) } println("avg = ${total.toDouble() / count}") // avg = 3.0 // runningFold โ€” yields the accumulator at each step (Kotlin 1.4+) val running = nums.runningFold(0) { acc, n -> acc + n } println(running) // [0, 1, 3, 6, 10, 15] // scan โ€” alias for runningReduce (uses first element as seed) println(nums.scan("") { acc, n -> "$acc$n" }) // [, 1, 12, 123, 1234, 12345] }