On Thu, 21 Mar 2019 at 15:21, Robert Hickman <robehick...@gmail.com> wrote:

> In this case nextIf() would have to be implemented something like:
>
> function nextif($someCondition) {
>     foreach($this->iteratorValue as $x) {
>         if(<some comparison of $x and $$someCondition) {
>              yield $x;
>         }
>     }
> }
>
> iterator_to_array would need an internal loop to pull the values from
> the generator.



I think it would be more like this:

function nextif($someCondition) {
    do {
        $this->currentIndex++;
        $x = $this->items[ $this->currentIndex ];
    } while ( ! some comparison of $x and $$someCondition);
    return $x;
}

nextIf() wouldn't be a generator, it would be a normal function returning
one value.

There is a nested loop in that imaginary version, but only because you
can't indicate "don't return anything"; given we're in imaginary concept
land, we could add that, and all sign of inner loops disappears:

function nextif($someCondition) {
   $this->currentIndex++;
   $x = $this->items[ $this->currentIndex ];
   if ( some comparison of $x and $$someCondition) {
       return $x;
   } else {
       return SKIP_THIS_ITEM;
   }
}





> Thus, as far as I can see, the generator implementation
> would result in two loops running in lock step, rather than only one
> in the eager case.
>


It's more like a pipeline: there's a single loop pumping data in, and at
any time there's a single "current item", which is either being checked
against the condition, manipulated in some way, or passed out the other
end. Each stage in the pipeline doesn't need to track what "current item"
means, it's given an input each time the loop cycles.

We write that as "foreach ( $previousStage as $x ) { yield $x; }" because
it's a familiar syntax, but really we're just defining the logic for a
nextStep($x) function.


Regards,
-- 
Rowan Collins
[IMSoP]

Reply via email to