note 129568 added to language.generators.syntax
| From: | HayleyWatson | Date: | Sun, 09 Jun 2024 02:17:44 +0000 |
| Subject: | note 129568 added to language.generators.syntax | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221367@lists.php.net to get a copy of this message | ||
If your generator works by setting up another generator and then iterating through it with
"yield from", without yielding anything of its own, you could just return the other
generator and save yourself a whole layer of delegation.
<?php
function first_generator(int $a, int $b): Generator
{
for($i = $a; $i < $b; ++$i)
yield $i * $i;
}
function second_generator(int $a, int $b): Generator
{
if($a > $b) [$a, $b] = [$b, $a];
// The last statement is the only thing that
// makes second_generator a generator
yield from first_generator(2 * $a, 2 * $b);
}
foreach(second_generator(4, 2) as $j) echo "$j\n";
?>
Once it starts iterating, the only thing second_generator is doing is delegating to first_generator
and passing along what it gets back unchanged. second_generator can be made into an ordinary
function that simply returns a suitably-constructed instance of first_generator to be iterated over
directly. It's literally just a matter of replacing "yield from" with
"return":
<?php
function first_generator(int $a, int $b): Generator
{
for($i = $a; $i < $b; ++$i)
yield $i * $i;
}
function second_generator(int $a, int $b): Generator
{
if($a > $b) [$a, $b] = [$b, $a];
return first_generator(2 * $a, 2 * $b);
}
foreach(second_generator(4, 2) as $j) echo "$j\n";
?>
Skipping that extra level of iteration.
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 222.152.65.7)
----
Manual Page -- https://php.net/manual/en/language.generators.syntax.php
Edit -- https://main.php.net/note/edit/129568
Del: integrated -- https://main.php.net/note/delete/129568/integrated
Del: useless -- https://main.php.net/note/delete/129568/useless
Del: bad code -- https://main.php.net/note/delete/129568/bad+code
Del: spam -- https://main.php.net/note/delete/129568/spam
Del: non-english -- https://main.php.net/note/delete/129568/non-english
Del: in docs -- https://main.php.net/note/delete/129568/in+docs
Del: other reasons-- https://main.php.net/note/delete/129568
Reject -- https://main.php.net/note/reject/129568
Search -- https://main.php.net/manage/user-notes.php