We need something like this:
private val fibSeq = lazySequence(1) { i, f ->
f(i - 1) + f(i - 2)
}
fun fib(i: Int) =
fibSeq[i - 2]
An example implementation:
interface IndexableSequence<T>: Sequence<T> {
operator fun get(index: Int): T
}
fun <T> lazySequence(z: T, f: (Int, (Int) -> T) -> T): IndexableSequence<T> =
object : IndexableSequence<T> {
val map = mutableMapOf(0 to z)
fun comp(iIn: Int): T {
val i = max(0, iIn)
return map[i] ?: f(i, ::comp).also { map[i] = it }
}
override fun get(index: Int) = comp(index)
override fun iterator(): Iterator<T> =
object : Iterator<T> {
override fun hasNext() = true
private var i = 0
override fun next(): T =
comp(i ++)
}
}
If something like that already exists, tell me. I don’t know every function inside of the Kotlin standard library.