Last active
August 29, 2015 14:11
-
-
Save alco/75fabd5849533110f058 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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