On Sun, Aug 12, 2012 at 5:56 PM, Brian Moon <br...@moonspot.net> wrote: > On 8/12/12 5:33 PM, Levi Morrison wrote: >> >> On Sun, Aug 12, 2012 at 2:08 PM, Brian Moon <br...@moonspot.net> wrote: >>> >>> Do 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. > > > 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.
No, Brian, it is 106 lines of actual code I would find in the wild. And sure, I'd have spaced the generator code more like: public function getIterator() { if ($this->left) { yield* $this->left; } if ($this->right) { yield* $this->right; } yield $this->value; } However, that's 11 lines of code compared to 106. > In the above example, what > sets $this->right? or $this->left? Iterators don't set $this->right and $this->left; they only traverse the tree. > I don't consider this a very good example. That's fine. You are entitled to your opinion. However, you didn't have to figure out the 106 lines of code that is the Post-Order iterator. That was a NIGHTMARE and I'm still not 100% confident that it works as it is supposed to. The generator, on the other hand, is simple and follows the definition very closely. MUCH better. -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: http://www.php.net/unsub.php