Skip to content

Instantly share code, notes, and snippets.

@timyates
Last active October 31, 2017 15:11
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timyates/edd6a6ab01a5200a73f4e031e11da94e to your computer and use it in GitHub Desktop.
Save timyates/edd6a6ab01a5200a73f4e031e11da94e to your computer and use it in GitHub Desktop.
Repeating Sequences in Kotlin
// Version using experimental co-routines in 1.1 thanks to @voddan on Slack
import kotlin.coroutines.experimental.buildSequence
fun <T> Sequence<T>.repeat() : Sequence<T> = buildSequence {
while(true) yieldAll(this@repeat)
}
fun main(args: Array<String>) {
sequenceOf(1, 2, 3).repeat().take(6).forEach { i -> println(i) }
}
class RepeatingSequence<T> constructor(val sequence : Sequence<T>) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
var iterator = sequence.iterator()
override fun next(): T {
val result = iterator.next()
if (!iterator.hasNext()) {
iterator = sequence.iterator()
}
return result
}
override fun hasNext(): Boolean {
return iterator.hasNext()
}
}
}
fun <T> Sequence<T>.repeat() : Sequence<T> = RepeatingSequence(this)
fun main(args: Array<String>) {
sequenceOf(1, 2, 3).repeat().take(6).forEach { i -> println(i) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment