Sequences: Can Be Infinite

Thanks to the fact that sequences do processing on demand, we can have infinite sequences. A typical way to create an infinite sequence is using sequence generators like generateSequence or sequence.

generateSequence example

Code

package com.glassthought.sandbox

import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
  val seedValue = 1
  
  generateSequence(seedValue) { it + 1 }
    .take(10)
    .forEach { print("$it, ") }
}

Command to reproduce:

gt.sandbox.checkout.commit 262033ba438658622981 \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run --quiet"

Recorded output of command:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 
Fibonacci example: using 'sequence'

Code

package com.glassthought.sandbox

import gt.sandbox.util.output.print
import gt.sandbox.util.output.printGreen
import gt.sandbox.util.output.println
import kotlinx.coroutines.runBlocking
import java.math.BigDecimal


// Declare a sequence of Fibonacci numbers, using BigDecimal
// to handle large values.
val fibonacci: Sequence<BigDecimal> = sequence {
  // Initialize the first two Fibonacci numbers.
  var current = 1.toBigDecimal()  // Current number in the sequence
  var prev = 1.toBigDecimal()     // Previous number in the sequence

  // Emit the first Fibonacci number (1).
  yield(prev)

  // Use an infinite loop to generate subsequent numbers.
  while (true) {
    // Emit the current Fibonacci number.
    yield(current)

    // Compute the next Fibonacci number by adding the previous two numbers.
    val temp = prev        // Temporarily store the previous number
    prev = current         // Update the previous number to the current one
    current += temp        // Update the current number to the sum of current and previous
  }
}

fun main() = runBlocking {
  fibonacci.take(10).toList().println()

  System.out.flush()
}

Command to reproduce:

gt.sandbox.checkout.commit d48a6563eadebbd18ccf \
&& cd "${GT_SANDBOX_REPO}" \
&& cmd.run.announce "./gradlew run --quiet"

Recorded output of command:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]


Backlinks