On Sun, Aug 12, 2012 at 8:25 PM, Brian Moon <br...@moonspot.net> wrote:
>>> 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.
>
>
> Could you show the whole class that this public function belongs to? I don't
> see how this function fits in and compares at all to the class you linked.
>
> Brian.

It renders the iterator class completely obsolete; it could be part of
the Binary Search Tree class.

If you still wanted a separate class (separation of concerns, perhaps)
it would look something like this (not sure on exact yield syntax):

class PostOrderIterator implements IteratorAggregate {

    /**
     * @var BinaryTree
     */
    protected $root;

    public function __construct(BinaryTree $root) {
        $this->root = $root;
    }

    /**
     * @link http://php.net/manual/en/iteratoraggregate.getiterator.php
     * @return Traversable
     */
    public function getIterator() {
        yield $this->traverse($this->root);
    }

    private function traverse(BinaryTree $node) {
        if ($node->left) {
            yield* $node->left;
        }

        if ($node->right) {
            yield* $node->right;
        }

        yield $node->value;
    }
}

All this does is take the node that acts as root in it's constructor
and then calls the generator with root as the starting point. That's
34 lines of code including comments and whitespace.

-- 
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php

Reply via email to