Skip to content

Instantly share code, notes, and snippets.

@alco
Last active August 29, 2015 14:11
Show Gist options
  • Save alco/75fabd5849533110f058 to your computer and use it in GitHub Desktop.
Save alco/75fabd5849533110f058 to your computer and use it in GitHub Desktop.
defmodule SieveStream do
def primes do
Stream.iterate(2, & &1 + 1)
|> Stream.transform([], fn nat, primes ->
if has_multiple(primes, nat) do
{[], primes}
else
{[nat], [nat | primes]}
end
end)
end
def unfold_primes do
Stream.unfold({2, []}, fn {nat, primes} ->
prime =
Stream.iterate(nat, & &1 + 1)
|> Enum.find(& not has_multiple(primes, &1))
{prime, {prime+1, [prime | primes]}}
end)
end
def has_multiple(numbers, num) do
Enum.any?(numbers, & rem(num, &1) == 0)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment