Yield from function?

Ivan Kazmenko via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jan 31 06:03:09 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.

Sounds like opApply (external iteration) may well be the way to 
go.
It is a great tool to separate (possibly complex) iteration logic 
from (possibly complex) instance processing logic.
Here is a random recipe: 
https://www.sociomantic.com/blog/2010/06/opapply-recipe

An example:

-----
import std.stdio;

class Node {
	int value;
	Node left, right;
	this (int value_) {value = value_;}
}

struct InOrderViewer {
	Node root;
	int opApply (int delegate (Node) process) {
		void recur (Node cur) {
			if (cur is null) return;
			recur (cur.left);
			process (cur); // use return value here to allow break in 
foreach
			recur (cur.right);
		}
		recur (root);
		return 0;
	}
}

void main () {
	auto v1 = new Node (1);
	auto v2 = new Node (2);
	auto v3 = new Node (3);
	auto v4 = new Node (4);
	auto v5 = new Node (5);
	v2.left = v1;
	v2.right = v5;
	v5.left = v3;
	v3.right = v4;

	foreach (node; InOrderViewer (v2)) {
		writeln (node.value ^^ 2); // 1 4 9 16 25
	}
}
-----

Ivan Kazmenko.



More information about the Digitalmars-d-learn mailing list