Range to Nullable conversion

Paul Backus snarwin at gmail.com
Fri Jun 10 18:00:20 UTC 2022


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);
}
```


More information about the Digitalmars-d-learn mailing list