An infinite iterator can keep the current index and triangular value:
val triangular = new Iterator[BigInt] {
  private var n = BigInt(0)
  private var total = BigInt(0)
  def hasNext: Boolean = true
  def next(): BigInt = {
    val result = total
    n += 1
    total += n
    result
  }
}
println(triangular.take(8).toList)
Before each call, total is the triangular number . Returning it and then using preserves this invariant. The prefix is . Arbitrary-precision integers prevent wraparound as the indefinitely available iterator advances.

Articles by others on the same topic (0)

There are currently no matching articles.