[your code here]

Dukc ajieskola at gmail.com
Mon Sep 27 18:21:24 UTC 2021


I sometimes feel that D is a bit weak when it comes to 
representing and handling dynamic tree-like data. However, I 
goofed around a bit and found that the newly added `std.sumtype` 
can get D quite far in that regard:

```D
import std.sumtype;
alias Node = SumType!(string, This[]);
Node node(T...)(T args){
     auto result = new Node[args.length];
     foreach(i, arg; args) result[i] = arg;
     return Node(result);
}

void print(Node n){
     import std.algorithm, std.stdio;
     n.match!(
         (string s) => write(s, " "),
         (Node[] ns){"[".write; ns.each!print; "] ".write;}
     );
}
void main(){
     node(
         "top-level", node("subtree", node("with", "a", 
"subsubtree")),
         node, node, node // three empty elements
     ).print;
}
```


More information about the Digitalmars-d mailing list