Skip to content

Instantly share code, notes, and snippets.

@aanand
Last active December 14, 2015 04:59
Show Gist options
  • Save aanand/5031784 to your computer and use it in GitHub Desktop.
Save aanand/5031784 to your computer and use it in GitHub Desktop.
Un-genuine Sieve of Eratosthenes in Haskell
$ ghci sieve.hs
*Main> take 10 primes
[2,3,5,7,11,13,17,19,23,29]
primes = sieve [2..]
sieve (x:xs) = x : sieve [n | n <- xs, n `mod` x > 0]
@FranklinChen
Copy link

Or, using a strict language such as Scala:

import scala.math.BigInt

object Sieve extends App {
  def sieve(stream: Stream[BigInt]) : Stream[BigInt] = stream match {
    case x #:: xs =>
      x #:: sieve(
        for {
          n <- xs
          if (n % x > 0)
        } yield n
      )
  }

  def bigIntsFrom(n: BigInt): Stream[BigInt] = n #:: bigIntsFrom(n+1)

  val primes = sieve(bigIntsFrom(2))

  primes take 10 foreach println
}

@raganwald
Copy link

It turns out there is an authoritative explanation for why this Haskell isn't the Sieve of Eratosthenes!

Great read: The Genuine Sieve of Eratosthenes

@aanand
Copy link
Author

aanand commented Feb 25, 2013

primes take 10 foreach println is equivalent to primes.take(10).foreach(println), right? Oh, Scala.

@aanand
Copy link
Author

aanand commented Feb 25, 2013

Nice find Reg. I love that the example code is identical to the one I typed from memory (disregarding whitespace and variable identifiers).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment