Inspired by IntStream.iterate in modern versions of Java, I was interested in having function that would create a sequence of values that could be specified and would behave much like a classic indexed for loop. I cobbled something up using generateSequence, but I'm wondering if there is something in the actual standard library that does something close to this already...
fun <T> iterate(seed: T, predicate: (T) -> Boolean, transform: (T) -> T): Sequence<T> {
var current = seed
return generateSequence() {
if (!predicate(current)) null
else {
val was = current
current = transform(was)
was
}
}
}
val seq: Sequence<Int> = iterate(0, { it < 1000 }, { it * 2 + 1 })
fun main() { println(seq.toList()) }
[0, 1, 3, 7, 15, 31, 63, 127, 255, 511]