Skip to content

Instantly share code, notes, and snippets.

@rbonvall
Created January 12, 2018 21:15
Show Gist options
  • Save rbonvall/25262a19b45b9f7cdbb144677a3d269e to your computer and use it in GitHub Desktop.
Save rbonvall/25262a19b45b9f7cdbb144677a3d269e to your computer and use it in GitHub Desktop.
Kolakoski prototype
val integers = Stream.from(0)
object E1 {
val evenIntegers = integers.filter(_ % 2 == 0)
}
object E2 {
val evenIntegers = integers.map(_ * 2)
}
object E3 {
val evenIntegers = Stream.iterate(0)(_ + 2)
}
object E4 {
val evenIntegers: Stream[Int] = 0 #:: evenIntegers.map(_ + 2)
}
val firstEvenIntegers = 0 to 30 by 2
assert(E1.evenIntegers startsWith firstEvenIntegers)
assert(E2.evenIntegers startsWith firstEvenIntegers)
assert(E3.evenIntegers startsWith firstEvenIntegers)
assert(E4.evenIntegers startsWith firstEvenIntegers)
object Primes {
def isPrime(n: Int) = n > 1 && (2 to n / 2).forall(n % _ != 0)
val integers = Stream.from(0)
val primes = integers.filter(isPrime)
println(integers) // Stream(0, 1, 2, ?)
println(primes) // Stream(2, ?)
println(primes(4)) // 11
println(integers) // Stream(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ?)
println(primes) // Stream(2, 3, 5, 7, 11, ?)
}
Primes
val onesAndTwos = Stream.continually(List(1, 2)).flatten
def rest(kolakoski: Stream[Int]): Stream[Int] = {
kolakoski.drop(2) zip onesAndTwos flatMap { case (k, n) ⇒ Seq.fill(k)(n) }
}
val kolakoski: Stream[Int] = 1 #:: 2 #:: 2 #:: rest(kolakoski)
val expectedKolakoski = List(1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1)
expectedKolakoski.take(23) .mkString("")
kolakoski .take(23).toList.mkString("")
assert(kolakoski startsWith expectedKolakoski)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment