Implementing an immutable enumerator

Viewed 345

Consider the following possible interface for an immutable generic enumerator:

interface IImmutableEnumerator<T>
{
    (bool Succesful, IImmutableEnumerator<T> NewEnumerator) MoveNext();
    T Current { get; }
}

How would you implement this in a reasonably performant way in c#? I'm a little out of ideas, because the IEnumerator infrastructure in .NET is inherently mutable and I can't see a way around it.

A naive implementation would be to simply create a new enumerator on every MoveNext() handing down a new inner mutable enumerator with current.Skip(1).GetEnumerator() but that is horribly inefficient.

I'm implementing a parser that needs to be able to look ahead; using an immutable enumerator would make things cleaner and easier to follow so I'm curious if there is an easy way to do this that I might be missing.

The input is an IEnumerable<T> and I can't change that. I can always materialize the enumerable with ToList() of course (with an IList in hand, looking ahead is trivial), but the data can be pretty large and I'd like to avoid it, if possible.

2 Answers
Related