Reputation: 77
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
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