Skip to content

Instantly share code, notes, and snippets.

@CattenLinger
Created May 30, 2021 15:43
Show Gist options
  • Save CattenLinger/93d3142676935325b343984d23943c12 to your computer and use it in GitHub Desktop.
Save CattenLinger/93d3142676935325b343984d23943c12 to your computer and use it in GitHub Desktop.
An iterator implementation that produces numbers from the Fibonacci sequence.
import java.math.BigDecimal
class FibonacciIterator : Iterator<BigDecimal> {
var generations = 0L
private set
private var ancient = BigDecimal(0)
private var parents = BigDecimal(1)
override fun hasNext(): Boolean {
return generations < Long.MAX_VALUE
}
override fun next(): BigDecimal {
return when(generations) {
0L -> ancient
1L -> parents
else -> (ancient + parents).also {
ancient = parents
parents = it
}
}.also { generations++ }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment