Richard Zhao
Richard Zhao

Reputation: 77

How can I create recursive generator in dart?

For example, I want to write a generator to iterate a tree. Can I use recursive function call?

Iterator<node> forallchildren(node) {
    for (var n in node.children) {
       yield n;
       forallchildren(n);
    }
}

Looks like the recursive call only generate iterator but not act like traverse the tree. Is there a better way?

Upvotes: 1

Views: 1087

Answers (1)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76243

You can only use yield in a function returning Iterable (not Iterator) if you mark the function with sync*.

Moreover to yield elements from an Iterable you have to use yield*.

So you can write your code like:

Iterable<Node> forallchildren(Node node) sync* {
    for (var n in node.children) {
       yield n;
       yield* forallchildren(n);
    }
}

Upvotes: 6

Related Questions