Last active
February 15, 2020 17:12
-
-
Save zonuexe/b2b4f3055df183f4682601af4492b6c6 to your computer and use it in GitHub Desktop.
ジェネレータで無限を手玉に取る修行
This file contains hidden or 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 | |
| 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; | |
| } | |
| } |
This file contains hidden or 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 | |
| function fizzbuzz_genA() | |
| { | |
| for ($i = 1; $i <= 100; $i++) { | |
| yield fizzbuzz($i); | |
| } | |
| } | |
| foreach (fizzbuzz_genA() as $fizzbuzz) { | |
| echo $fizzbuzz, PHP_EOL; | |
| } |
This file contains hidden or 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 | |
| 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; | |
| } |
This file contains hidden or 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 | |
| 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