foreach multiple loop sugar

ixid via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Aug 18 08:51:53 PDT 2015


Though sugar seems to be somewhat looked down upon I thought I'd 
suggest this- having seen the cartesianProduct function from 
std.algorithm in another thread I thought it would be an 
excellent piece of sugar in the language. It's not an earth 
shattering change but it makes something very common more elegant 
and reduces indentation significantly for multiple nested loops. 
Braces make nested loops very messy and any significant quantity 
of code in the loop body benefits from not being in a messy 
nesting.

import std.algorithm, std.range, std.stdio;


void main() {
	// Standard
	foreach(i; 0..10)
		foreach(j; 0..10)
			foreach(k; 0..10)
				writeln(i, j, k);
	
	// Better
	foreach(k, j, i; cartesianProduct(10.iota, 10.iota, 10.iota))
		writeln(i, j, k);
	
	
	// Sugar
	foreach(k, j, i; 0..10, 0..10, 0..10)
		writeln(i, j, k);

         //Following brace rules
	// Standard
	foreach(i; 0..10)
	{
		foreach(j; 0..10)
		{
			foreach(k; 0..10)
			{
				writeln(i, j, k);
			}
		}
	}
		
	// Sugar
	foreach(k, j, i; 0..10, 0..10, 0..10)
	{
		writeln(i, j, k);
	}
}




More information about the Digitalmars-d-learn mailing list