Skip to content

Instantly share code, notes, and snippets.

@drupol
Last active September 1, 2020 07:59
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/8513c7bfdbe1ad7d66fa710f51a21b32 to your computer and use it in GitHub Desktop.
Save drupol/8513c7bfdbe1ad7d66fa710f51a21b32 to your computer and use it in GitHub Desktop.
Minimalist Prime numbers generator in PHP (version >= 7.4) - Can you make it shorter?
<?php
/**
* Run this code with: "php -n <file.php>" to make sure no configuration will be used
* so xdebug will not be used either.
*/
declare(strict_types=1);
function primesGenerator(Iterator $iterator): Generator
{
yield $primeNumber = $iterator->current();
$iterator = new \CallbackFilterIterator(
$iterator,
fn(int $a): bool => $a % $primeNumber !== 0
);
$iterator->next();
return $iterator->valid() ?
yield from primesGenerator($iterator):
null;
}
function integerGenerator(int $init = 1, callable $succ): Generator
{
yield $init;
return yield from integerGenerator($succ($init), $succ);
}
$primes = primesGenerator(integerGenerator(2, fn(int $n): int => $n + 1));
foreach ($primes as $p) {
var_dump($p);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment