How do you safely deal with range.front?
Dukc
ajieskola at gmail.com
Sat Dec 30 23:38:04 UTC 2017
On Saturday, 30 December 2017 at 19:00:07 UTC, aliak wrote:
> Instead of this:
> auto result = range.op!f;
> if (!result.empty) {
> result.front.method();
> }
>
> This:
> range.op!f.ifFront.method();
Ah, so you don't have a problem with checking emptiness but you
want to do it inside the expression, without having to type the
range twice? I personally find it useful to define an "use"
template for cases like this:
import std.typecons : Nullable;
auto ref use(alias how, T)(T what){return how(what);}
void main()
{
import std.algorithm, std.range, std.stdio;
auto arr = [2, 3, 4];
foreach(unused; 0 .. 5)
{ arr
.map!(x => (x + 2) * x)
.use!(x => x.empty? 0: x.front)
.writeln;
if (arr.empty){} else arr.popFront;
}
readln(); //program termination delayed until pressing enter
}
/+
8
15
24
0
0
+/
Of course, if you want you can also define a more specialized
template which does not require typing the lambda function.
More information about the Digitalmars-d-learn
mailing list