Range to Nullable conversion
Antonio
antonio at abrevia.net
Fri Jun 10 18:26:56 UTC 2022
On Friday, 10 June 2022 at 18:00:20 UTC, Paul Backus wrote:
> On Friday, 10 June 2022 at 17:22:53 UTC, Antonio wrote:
>> Can this code be written as a **simple** expression? (without
>> having to write helper methods).
>
> ```d
> import std.range, std.typecons;
>
> Nullable!(ElementType!R) maybeFront(R)(auto ref R r)
> if (isInputRange!R)
> {
> if (r.empty)
> return typeof(return)();
> else
> return nullable(r.front);
> }
>
> unittest
> {
> int[] a = [1, 2, 3];
> int[] b;
>
> assert(a.maybeFront == nullable(1));
> assert(b.maybeFront.isNull);
> }
> ```
Nice (and simple) helper method.
Thank you Paul
More information about the Digitalmars-d-learn
mailing list