Core1: Iterators

[This post is part of a series, "wish-list for future versions of VB"]

 

IDEA: Add Iterators to VB. But don’t do them like C#; instead do them as “anonymous iterators”, as described by Paul Vick: https://www.panopticoncentral.net/archive/2008/08/08/24155.aspx

    Function FromTo(low As Integer, high As Integer) As IEnumerable(Of Integer)

        If low > high Then Throw New ArgumentException("low>high")

        Return Iterator

                   If low <= high Then

                       Yield low

                   Else

                       Yield Each FromTo(low + 1, high)

                   End If

               End Iterator

    End Function

One feature of this is that you can do argument-validation before returning the iterator; C# users currently have to write two methods, an outer one which validates and an inner one which is the iterator.

Another feature is to use a “Return Each” construct, rather than having to return each one individually.

 

SCENARIO: Iterators are just generally useful. As we rewrite the VB compiler and IDE from C++ into VB, we find ourselves needing iterators all the time. They would make it easier to do LINQ and a whole load of tree-like data-structures.

 

At PDC09, Luca Bolognese’s talk “Future Directions for VB and C#” touched on Async (jump to the 40 minute mark). I’ll blog about async ideas in a week (“Power2: Async and Resumable Methods”). For now, it’s worth nothing that Async and Iterators are both examples of “delayed-execution iterative code blocks” and should probably both be implemented with exactly the same machinery under the hood.

Eric Lippert has blogged about the scope of variables in a For loop: I’ll also blog about that in a week (“Req1: put loop control variable inside loop”). For now, I’ll just say that we should probably fix the for-loop-scope along with iterators.

 

Provisional evaluation from VB team: This is a decent idea, one that we should consider against the other decent ideas.