Re: [RFC] Generators
| From: | Brian Moon | Date: | Sun, 12 Aug 2012 23:56:49 +0000 |
| Subject: | Re: [RFC] Generators | ||
| References: | 1 2 3 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-62121@lists.php.net to get a copy of this message | ||
On 8/12/12 5:33 PM, Levi Morrison wrote:
On Sun, Aug 12, 2012 at 2:08 PM, Brian Moon <brian@moonspot.net> wrote:Well, it's 52 lines, not 106. The 5 lines above are not commented nor are they spaced at all like the ones in the class. In the above example, what sets $this->right? or $this->left? There has to be more calling code around this. I don't consider this a very good example. Brian. brianlmoon@php.netDo you have a good example usage other than a file? I don't find fopen/fgets/fclose all that complicated. What are the other valid use cases for such a thing?One fabulous use case is creating an iterator for a Binary Search Tree. A post order done without generators looks like: https://github.com/morrisonlevi/PHP-Datastructures/blob/master/src/Spl/PostOrderIterator.php. An iterator using a generator looks something like:public function getIterator() { if ($this->left) yield* $this->left; yield $this->value; if ($this->right) yield* $this->right; }This is 5 lines. The fully commented version of the post-order iterator previously mentioned is 106 lines of code and is considerably harder to understand.