Hi guys! Is there any way to exit-early/short-circ...
# functional
g
Hi guys! Is there any way to exit-early/short-circuit from the
reduce
function? I wan’t to reduce an infinite sequence of numbers, but only until some condition is met (based on the result of the reduce). I know Clojure has this neat
reduced
function for this. In Haskell we could use
scan
. But do we have anything similar in Kotlin’s stdlib?
a
It depends on the surroundings, for example this short-circuits `reduce`:
Copy code
fun reduced(list: Iterable<Int>): Int {
    return list.reduce { acc, item -> if(acc < 100) acc + item else return@reduced item }
}
u
I think people usually end up using recursion instead of reduce in these cases
p
The implementation of
reduce
uses recursion, or at least the ones in arrow do. For those that are not stack-safe we have tailrecM, which are a bit more involved