www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Is there any way to fix this elegant way to walk a tree at compile

reply Gareth Charnock <gareth.charnock gmail.com> writes:
I was trying to walk a tree at compile time and I came up with this 
method. It seems very elegant, but unfortunately it fails with a 
recursive alias declaration error. I have a bad feeling there's no way 
to fix this but I thought I'd ask in case anyone had any ideas.

(https://gist.github.com/783832 for syntax highlighting, easier on the eye)

import std.typetuple;

template staticReduce(alias F,T...) {
	static if(T.length==0) {
		alias TypeTuple!() staticReduce;
	} else static if(T.length==1) {
		enum staticReduce=T[0];
	} else {
	    enum staticReduce=staticReduce!(F,TypeTuple!(F!(T[0],T[1]),T[2..$]));
	}
}

template concan(string s1,string s2) {enum concan = s1 ~ s2;};
static assert(staticReduce!(concan,"Hello", " world")=="Hello world"); 
//passes


template Flatten(Tree,string s = "") {
	alias staticReduce!(concan,staticMap!(Flatten,Tree.ChildrenTuple)) Flatten;
}

struct TreeNode(Children...) {
	alias Children ChildrenTuple;
}

alias TreeNode!("A",TreeNode!("B","C","D"),"E") StaticTree;
static assert(Flatten!(StaticTree) == "ABCDE");
//Error: alias 
static_walk_tree.Flatten!(TreeNode!("A",TreeNode!("B","C","D"),"E")).Flatten 
recursive alias declaration
Jan 17 2011
parent Gareth Charnock <gareth.charnock gmail.com> writes:
On 18/01/11 01:30, Gareth Charnock wrote:
      alias staticReduce!(concan,staticMap!(Flatten,Tree.ChildrenTuple))
 Flatten;
Actually, this code is a little bit brain-dead. There's no stopping condition for the recursion and I'm not sure what I was trying to do with the second string s = "" template parameter. That should be handled by the template "return value". Must be getting late. Sorry.
Jan 17 2011