www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to mixin repeated text?

reply Andrey <saasecondbox yandex.ru> writes:
Hello again,
I have this part of code:
 ...
if(index + 3 >= data.length || data[index + 1][0] == '&' || 
data[index + 2][0] == '&' || data[index + 3][0] == '&' || 
data[index + 4][0] == '&')
{
    writeln("Some text...");
}
I don't want to write manually these four "or" conditions because in each case I know at compile time how many conditions should be. I would be great if I could do something like this:
if(index + 3 >= data.length || mixin OrCondition!4) { ... }
where "OrCondition" will insert text using this expression:
 data[index + j][0] == '&' // j is between [1 and 4]
I know that it is possible but don't know how to implement...
Aug 27 2018
parent reply Kamil Koczurek <koczurekk gmail.com> writes:
On Monday, 27 August 2018 at 11:52:02 UTC, Andrey wrote:
 Hello again,
 I have this part of code:
 ...
if(index + 3 >= data.length || data[index + 1][0] == '&' || 
data[index + 2][0] == '&' || data[index + 3][0] == '&' || 
data[index + 4][0] == '&')
{
    writeln("Some text...");
}
I don't want to write manually these four "or" conditions because in each case I know at compile time how many conditions should be. I would be great if I could do something like this:
if(index + 3 >= data.length || mixin OrCondition!4) { ... }
where "OrCondition" will insert text using this expression:
 data[index + j][0] == '&' // j is between [1 and 4]
I know that it is possible but don't know how to implement...
Mixins seem to be an overkill here. Maybe something like this would suffice: data[index + 1 .. index + 5].map!(k => k[0]).array == "&&&&"
Aug 27 2018
parent Andrey <saasecondbox yandex.ru> writes:
On Monday, 27 August 2018 at 11:56:08 UTC, Kamil Koczurek wrote:
 Mixins seem to be an overkill here. Maybe something like this 
 would suffice:

 data[index + 1 .. index + 5].map!(k => k[0]).array == "&&&&"
Here there is dynamic code, with memory allocs. I found solution: ----------------------- import std.meta; import std.traits; import std.stdio; import std.array : join; import std.algorithm.iteration : map; import std.conv : to; import std.range; string qaz(alias args, alias index, ubyte count)() { return iota(1, count).map!(j => args.stringof ~ '[' ~ index.stringof ~ '+' ~ j.to!string ~ "][0] == '&'").join("||"); } void main() { ushort index = 1; string[] args = ["&second", "123", "&qaz", "true", "&first", "77", "&value"]; if(index + 1 >= args.length || mixin(qaz!(args, index, 4))) { writeln(qaz!(args, index, 4)()); } } -----------------------
Aug 27 2018