Thread overview | |||||
---|---|---|---|---|---|
|
August 27, 2018 How to mixin repeated text? | ||||
---|---|---|---|---|
| ||||
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... |
August 27, 2018 Re: How to mixin repeated text? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Andrey | 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 == "&&&&"
|
August 27, 2018 Re: How to mixin repeated text? | ||||
---|---|---|---|---|
| ||||
Posted in reply to Kamil Koczurek | 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)());
}
}
-----------------------
|
Copyright © 1999-2021 by the D Language Foundation