www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - static foreach direct use of variables

reply Michelle Long <HappyDance321 gmail.com> writes:
auto foo(S s)
{
	static foreach(k, p; [s, this])
		for(int i = 0; i < p.length; i++)
         		...
}

The idea is to provide single for loop structure for each of the 
variables(in this case s and this).

The is to avoid string mixins which are pathetic for this kind of 
work.

The point is that instead of having to do

		for(int i = 0; i < s.length; i++)
                  ...
		for(int i = 0; i < this.length; i++)
                  ...

in which case ... might be very long.

Sure one can create a function and all that mess but the compiler 
should be able to do symbol replacement very naturally and easily.
Jan 01 2019
next sibling parent Adam D. Ruppe <destructionator gmail.com> writes:
On Tuesday, 1 January 2019 at 21:14:09 UTC, Michelle Long wrote:
 auto foo(S s)
 {
 	static foreach(k, p; [s, this])
 		for(int i = 0; i < p.length; i++)
         		...
 }
try static foreach(.......) {{ stuff }} The double {{ and double }} are intentional.
Jan 01 2019
prev sibling parent reply Paul Backus <snarwin gmail.com> writes:
On Tuesday, 1 January 2019 at 21:14:09 UTC, Michelle Long wrote:
 auto foo(S s)
 {
 	static foreach(k, p; [s, this])
 		for(int i = 0; i < p.length; i++)
         		...
 }

 The idea is to provide single for loop structure for each of 
 the variables(in this case s and this).
You can do this with `std.meta.AliasSeq`: string[] a = ["lions", "tigers", "bears"]; int[] b = [123, 456, 789]; static foreach(array; AliasSeq!(a, b)) { foreach (item; array) { writeln(item); } }
Jan 01 2019
parent Michelle Long <HappyDance321 gmail.com> writes:
On Tuesday, 1 January 2019 at 21:34:08 UTC, Paul Backus wrote:
 On Tuesday, 1 January 2019 at 21:14:09 UTC, Michelle Long wrote:
 auto foo(S s)
 {
 	static foreach(k, p; [s, this])
 		for(int i = 0; i < p.length; i++)
         		...
 }

 The idea is to provide single for loop structure for each of 
 the variables(in this case s and this).
You can do this with `std.meta.AliasSeq`: string[] a = ["lions", "tigers", "bears"]; int[] b = [123, 456, 789]; static foreach(array; AliasSeq!(a, b)) { foreach (item; array) { writeln(item); } }
I tried that but it didn't work... I will try again.
Jan 01 2019