https://kotlinlang.org logo
#functional
Title
# functional
g

gregd

12/02/2018, 10:53 AM
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

Andreas Sinz

12/02/2018, 11:43 AM
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

Uzi Landsmann

12/02/2018, 2:55 PM
I think people usually end up using recursion instead of reduce in these cases
p

pakoito

12/02/2018, 10:07 PM
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
5 Views