Yield from function?

TheFlyingFiddle via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Jan 30 14:34:11 PST 2017


On Monday, 30 January 2017 at 11:03:52 UTC, Profile Anaysis wrote:
> I need to yield from a complex recursive function too allow 
> visualizing what it is doing.
>
> e.g., if it is a tree searching algorithm, I'd like to yield 
> for each node so that the current state can be shown visually.
>
> I realize that there are several ways to do this but D a yield 
> version without additional threads would be optimal. I don't 
> need concurrency or speed, just simple.

If you don't want to use fibers then an alternative to yeilds is 
to use callbacks during iteration.

Example:
struct Tree(T)
{
    T value;
    Tree!(T)[] children;
}

void iterDepth(T)(Tree!(T) tree, void delegate(Tree!T) cb)
{
     cb(tree);
     foreach(child; tree.children)
     {
         iterDepth(child, cb);
     }
}

unittest
{
     auto tree = ... //Make the tree somehow
     iterDepth(tree, (node)
     {
         writeln(node.value);
     });
}

Callbacks have their set of problems but it's one of the simpler 
ways to do this.














More information about the Digitalmars-d-learn mailing list