Skip to content

Instantly share code, notes, and snippets.

@etam
Created March 15, 2017 15:20
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save etam/78f8765ad18fe25e29b402bce16ffc44 to your computer and use it in GitHub Desktop.
/*
primes = filterPrime [2..]
where filterPrime (p:xs) =
p : filterPrime [x | x <- xs, x `mod` p /= 0]
main = print $ take 10 primes
*/
#include <iostream>
#include <range/v3/all.hpp>
namespace r = ranges;
namespace rv = r::view;
template <typename Rng, typename Fun>
auto lazy(Rng&& rng, Fun&& fun)
{
return rv::single(rng) | rv::transform(fun) | rv::join;
}
template <typename T>
r::any_view<T> filterPrime(r::any_view<T> rng)
{
const auto p = r::front(rng);
return rv::concat(
rv::single(p),
lazy(rng | rv::tail | rv::remove_if([=](auto x){ return x % p == 0; }),
[](auto&& xs) { return filterPrime<T>(xs); })
);
}
auto primes()
{
return filterPrime<int>(rv::ints(2));
}
int main()
{
std::cout << (primes() | rv::take(1000)) << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment