Last active
September 1, 2020 07:59
-
-
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?
This file contains 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
<?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