Thread overview
foreach change for multi-dimensional data
Jan 28, 2016
ixid
Jan 28, 2016
Ali Çehreli
Jan 28, 2016
ixid
January 28, 2016
This is an idle thought hence putting it on the Learn-level forum. An idea struck me for foreach to make working with more complicated data types or heavily nested data easier.


	uint[][] a = [[1,2,3],[4,5,6]];

	foreach(uint[] b; a)
		b.writeln;
	

At present you can specify the type of 'b' in this example. If you want to iterate over each uint you have to write (and obviously you can omit the type for 'b' and 'c'):

	
	foreach(uint[] b; a)
		foreach(uint c; b)
			c.writeln;
	
It would be nice if you could do something like this:

	foreach(uint c; a)
		c.writeln;

Where it will take the ForeachType of 'a' until it finds a match to the type of 'c' and iterate over all that data. It would make it much less messy to apply a function that takes uint to all the data rather than having to nest loops or map maps.
January 28, 2016
On 01/28/2016 05:33 AM, ixid wrote:
> This is an idle thought hence putting it on the Learn-level forum. An
> idea struck me for foreach to make working with more complicated data
> types or heavily nested data easier.
>
>
>      uint[][] a = [[1,2,3],[4,5,6]];

[...]

> It would be nice if you could do something like this:
>
>      foreach(uint c; a)
>          c.writeln;

It looks like Solomon E's recent collapse() is what we need here:

  http://forum.dlang.org/post/xihlsfgfpykdvmvrggyr@forum.dlang.org

    foreach(c; a.collapse)
        // ...

Ali

January 28, 2016
On Thursday, 28 January 2016 at 15:38:20 UTC, Ali Çehreli wrote:
> On 01/28/2016 05:33 AM, ixid wrote:
> > This is an idle thought hence putting it on the Learn-level
> forum. An
> > idea struck me for foreach to make working with more
> complicated data
> > types or heavily nested data easier.
> >
> >
> >      uint[][] a = [[1,2,3],[4,5,6]];
>
> [...]
>
> > It would be nice if you could do something like this:
> >
> >      foreach(uint c; a)
> >          c.writeln;
>
> It looks like Solomon E's recent collapse() is what we need here:
>
>   http://forum.dlang.org/post/xihlsfgfpykdvmvrggyr@forum.dlang.org
>
>     foreach(c; a.collapse)
>         // ...
>
> Ali

That's a much more limited version of what I'm suggesting in that it just collapses until something isn't an array any more, sometimes you might only want to collapse two levels and get up with something that's still an array type or you will be getting members in struct that's in an array.

I've written something similar for myself that will collapse until a provided type is matched or the first argument type of a provided function is matched and apply the function.