Last active
October 31, 2017 15:11
-
-
Save timyates/edd6a6ab01a5200a73f4e031e11da94e to your computer and use it in GitHub Desktop.
Repeating Sequences in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) } | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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