On Monday, 26 October 2015 at 18:46:45 UTC, Dandyvica wrote:
Hi all,

I'm trying to find out a solution to implement a generic tree or array container whose nodes
can either be elements or a subtree (or sub-array).

Pretty much like you can do in Python:

l = [1, 2, [1, 2, 3], 4]

l is a list of (integers or list of integers).

Any idea on how to do that?

Thanks.

It's a bit more involved than in Python as D is not a dynamically typed language.

import std.typecons;
import std.stdio;

struct Tree(T)
{
        T payload;
        Tree!T[] children;
}

Tree!T tree(T)(T payload, Tree!T[] children...)
{
        return Tree!T(payload, children.dup);
}

//Convenience overload because typeof(null)
//does not implicitly convert to Tree!T[]
Tree!T tree(T)(T payload, typeof(null))
{
        return Tree!T(payload, null);
}

void printTree(T)(Tree!T tree)
{
        writeln(tree.payload);
        foreach (child; tree.children)
        {
                printTree(child);
        }
}

void main()
{
        auto intTree = tree(0,
                           tree(1,
                               tree(2)),
                           tree(3,
                               tree(4,
                                   tree(5))),
                           tree(6,
                               tree(7)));

        printTree(intTree);
}

Otherwise, you an use std.variant.Variant or std.variant.Algebraic.

Reply via email to