Solution

ID: past-exam-of-the-year-1-of-the-computer-science-course-of-the-university-of-oxford/2017/imperative-programming-resit/6/b/solution

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.

New to topics? Read the docs here!