cheezsteak
cheezsteak

Reputation: 2917

Reverse the behavior of `IEnumerator`

I'm writing an Iterator interface in C# which behaves the same as an IEnumerator but the it has a different signature

public interface Iterator
{
    /// <summary>
    /// Check if there iterator has another value.
    /// </summary>
    /// <returns><c>true</c>, if there is another value <c>false</c> otherwise.</returns>
    bool hasNext();

    /// <summary>
    /// Move the iterator to the next object and return that object.
    /// </summary>
    /// <returns>The next object.</returns>
    object next();
}

which is backwards from the IEnumerator behavior of MoveNext and Current. If I have a implementation that simply wraps an IEnumerator as my Iterable

class EnumeratorWrap: Iterator
{
    private IEnumerator<object> _iter;
    private bool _hasNext = true;

    public Enumerator(IEnumerator<object> iter)
    {
        _iter = iter;
    }

    override public bool hasNext() 
    {
        return _hasNext;
    }

    override public object next()
    {
        _hasNext = _iter.MoveNext();
        return _iter.Current;
    }
}

but it doesn't work in the case of an empty enumerator because hasNext will return true when it really is false and I don't know how to check if the enumerator is empty without mutating the enumerator. How can I?

Upvotes: 0

Views: 451

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660159

I don't know how to check if the enumerator is empty without mutating the enumerator. How can I?

You can't.

So how do you solve the problem?

class EnumeratorWrap: Iterator
{
    private IEnumerator _iter;
    private bool _hasNext;
    private object _next;

    public EnumeratorWrap(IEnumerator iter)
    {
        _iter = iter;
        Next();
    }

    public bool HasNext() 
    {
        return _hasNext;
    }

    public object Next()
    {
        object current = _next;
        _hasNext = _iter.MoveNext();
        _next = _hasNext ? _iter.Current : null;
        return current;
    }
}

The moral of the story: ask about solving problems, not about how to do some impossible thing that you think you need to do to solve the problem. Odds are good that you don't actually need to do that thing.

Upvotes: 5

Related Questions