Skip to content

Instantly share code, notes, and snippets.

@drupol
Last active December 30, 2020 17:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drupol/cb6a4bb77bd13f5e7ffe483c770273cc to your computer and use it in GitHub Desktop.
Save drupol/cb6a4bb77bd13f5e7ffe483c770273cc to your computer and use it in GitHub Desktop.
Generating Prime Numbers with loophp/collection
<?php
declare(strict_types=1);
include __DIR__ . '/../vendor/autoload.php';
use loophp\collection\Collection;
$integers = Collection::unfold(static fn (int $n = 1): int => $n + 1);
$primes = static function (Collection $collection) use (&$primes): Generator {
yield $current = $collection->current();
return yield from $primes($collection->filter(static fn (int $i): bool => 0 !== $i % $current));
};
$primesCollection = Collection::fromIterable($primes($integers));
foreach ($primesCollection->limit(100) as $prime) {
var_dump($prime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment