Skip to content

Instantly share code, notes, and snippets.

@zonuexe
Last active February 15, 2020 17:12
Show Gist options
  • Select an option

  • Save zonuexe/b2b4f3055df183f4682601af4492b6c6 to your computer and use it in GitHub Desktop.

Select an option

Save zonuexe/b2b4f3055df183f4682601af4492b6c6 to your computer and use it in GitHub Desktop.
ジェネレータで無限を手玉に取る修行
<?php
function map(Closure $callback, iterable $iter): Generator
{
foreach ($iter as $k => $v) {
yield $k => $callback($v);
}
}
function take(int $n, iterable $iter): Generator
{
$i = 0;
foreach ($iter as $k => $x) {
if ($n <= $i++) { break; }
yield $k => $x;
}
}
<?php
function fizzbuzz_genA()
{
for ($i = 1; $i <= 100; $i++) {
yield fizzbuzz($i);
}
}
foreach (fizzbuzz_genA() as $fizzbuzz) {
echo $fizzbuzz, PHP_EOL;
}
<?php
function fizzbuzz_genB(int $n, int $m)
{
yield from map(Closure::fromCallable('fizzbuzz'), xrange($n, $m));
}
foreach (fizzbuzz_genB(20, 80) as $fizzbuzz) {
echo $fizzbuzz, PHP_EOL;
}
<?php
function fizzbuzz_genC(int $n)
{
while (true) {
yield fizzbuzz($n++);
}
}
foreach (take(100, fizzbuzz_genC(60)) as $fizzbuzz) {
echo $fizzbuzz, PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment