Skip to content

Instantly share code, notes, and snippets.

@drupol
Created October 8, 2020 20:30
Show Gist options
  • Select an option

  • Save drupol/d82ca1d6a32fb5208e2f85fa3169c2ed to your computer and use it in GitHub Desktop.

Select an option

Save drupol/d82ca1d6a32fb5208e2f85fa3169c2ed to your computer and use it in GitHub Desktop.
primes.php with IteratorAggregate
<?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);
namespace App;
use Generator;
use Iterator;
use IteratorAggregate;
class PrimeGenerator implements IteratorAggregate
{
private $iterator;
public function __construct(Iterator $iterator)
{
$this->iterator = $iterator;
}
public function getIterator()
{
$this->iterator->next();
yield $primeNumber = $this->iterator->current();
yield from new PrimeGenerator(
new \CallbackFilterIterator(
$this->iterator,
fn(int $a): bool => $a % $primeNumber !== 0
)
);
}
}
function integerGenerator(int $init = 1, callable $succ): Generator
{
yield $init;
return yield from integerGenerator($succ($init), $succ);
}
$primes = new PrimeGenerator(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