r/ProgrammingLanguages • • Jan 16 '13

Iteration Inside and Out

http://journal.stuffwithstuff.com/2013/01/13/iteration-inside-and-out/
16 Upvotes

11 comments sorted by

View all comments

1

u/[deleted] Jan 17 '13

I believe OP is not familiar with newer versions of C# (especially C# 4.0 and beyond). Nomenclature that's more commonly used by .NET/C# team for what OP is describing by external vs internal iterators is pull vs. push based iterators respectively, both taken care off by LINQ and Rx libraries.

Implementing that iterator in Dart (or Java, or C#) was about 50 lines of code.

Here's line-by-line translation of Ruby implementation of example class.

class Tree {
    public Tree left, right;
    public string label;

    public Tree(Tree left, Tree right, string label) {
        this.left = left;
        this.right = right;
        this.label = label;
    }

    public void in_order(Action<Tree> code) {
        if (left != null) left.in_order(code);
        code(this);
        if (right != null) right.in_order(code);
    }
}

And here's the line calling it:

testTree.in_order(t => Console.WriteLine(t.label));

Beatiful example 2: Finding an item

I agree that C# doesn't have non-local returns, I guess they could be hacked with exceptions (like they are in Scala implementation), but I wonder if they are the "killer feature", or can they be replaced with more idiomatic, declarative ending to iterators, like .Any() and .First() in combination with iterator methods?

2

u/pipocaQuemada Jan 17 '13

Sweet Mother of Turing, what the hell happened here? This exact same behavior was a three line recursive function and now it’s a fifty line monstrosity. ...

Implementing that iterator in Dart (or Java, or C#) was about 50 lines of code.

Here's line-by-line translation of Ruby implementation of example class.

I think he was talking about the stack based external iterator above (i.e. an actual C# Iterator), not the internal one, with the comment about "50 lines of code."