How do I accumulate an operation by repeating x nu...
# stdlib
s
How do I accumulate an operation by repeating x number of times? Essentially,
2.repeat(init = 10) { acc -> acc * 10 } == 1_000
(to repeat 10*10 twice, or 10*10*10) instead of
(0..1).fold(10) { acc, _ -> acc * 10 } = 1_000
e
one option:
Copy code
generateSequence(seed = 10)  { acc -> acc * 10 }.drop(2).first() == 1_000
but I'd just write it with a
var
and loop; both fold and sequence create unnecessary iterators
certainly you could write your own
Copy code
inline fun <T> repeat(times: Int, seed: T, nextFunction: (T) -> T): T {
    var acc = seed
    repeat(times) { acc = nextFunction(acc) }
    return acc
}
but there's no standard function, and unfortunately due to the generic (even though it's inline) this results in unnecessary boxing
d
Does the boxing still happen if
T
is
reified
?
e
yes, reified just enables some more features