Fun with recursions

Andrej Mitrovic andrej.mitrovich at gmail.com
Fri Feb 21 16:49:15 UTC 2020


One of my pet peeves about ranges is that they are sometimes hard 
to compose with recursive data structures.

For example, let's say you have a data structure like this:

struct Node
{
     string name;
     int[] numbers;
     Node[] nodes;
}

Maybe you are interested in collecting all of the names of the 
nodes, starting from some root node. Or maybe you want the 
numbers instead. And you want a range, damn it!

It's very easy to write a recursive function manually, but then 
we're writing dumb iterative functions and that's no fun. :>

I can't think of any helper functionality in Phobos that would 
let me do this. So I wrote something of my own with Generators:

https://gist.github.com/AndrejMitrovic/282d062c09a6df697476a8304bb23c19


Here's what it looks like:

-----
Node node = { ... };

auto r1 = node.getRecursive!(n => n.numbers);
r1.each!(numbers => writeln(numbers));

auto r2 = node.getRecursive!(n => n.name);
r2.each!(name => writeln(name));
-----

It's very simplistic, but I think it could easily be expanded 
upon. And it could use a better name. It's possible I'm not 
seeing an easier solution though, so destroy if you must.


More information about the Digitalmars-d mailing list