Skip to content

Instantly share code, notes, and snippets.

@h0tk3y
Last active February 3, 2016 00:36
Show Gist options
  • Select an option

  • Save h0tk3y/6dda2b292d8804d72967 to your computer and use it in GitHub Desktop.

Select an option

Save h0tk3y/6dda2b292d8804d72967 to your computer and use it in GitHub Desktop.
import kotlin.system.measureTimeMillis
/**
* Created by igushs on 2/2/16.
*/
public operator fun <T> Sequence<T>.plus(otherGenerator: () -> Sequence<T>) =
object : Sequence<T> {
private val thisIterator: Iterator<T> by lazy { [email protected]() }
private val otherIterator: Iterator<T> by lazy { otherGenerator().iterator() }
override fun iterator() = object : Iterator<T> {
override fun next(): T =
if (thisIterator.hasNext())
thisIterator.next()
else
otherIterator.next()
override fun hasNext(): Boolean =
thisIterator.hasNext() || otherIterator.hasNext()
}
}
fun primes(): Sequence<Int> {
fun primesFilter(from: Sequence<Int>): Sequence<Int> = from.iterator().let {
val current = it.next()
sequenceOf(current) + { primesFilter(it.asSequence().filter { it % current != 0 }) }
}
return primesFilter((2..Int.MAX_VALUE).asSequence())
}
fun main(args: Array<String>) {
println(measureTimeMillis { primes().take(1000).toList() })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment