Writing a Fibonnaci iterator

The body of the iterator can be exactly the same as the one in the sequence:

val fibonacci = buildIterator {
yield(1L)
var current = 1L
var next = 1L
while (true) {
yield(next)
val tmpNext = current + next
current = next
next = tmpNext
}
}

So now we can easily, and on demand, get up to 92 numbers in the sequence from this iterator:

for (i in 0..91) {
println("$i is ${fibonacci.next()}")
}

If you are curious, these are the last few elements that can be calculated with this implementation:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.14.129.194