Return explicitly "empty" MapResult (fail-fast)
Paul Backus
snarwin at gmail.com
Thu Jan 1 17:09:20 UTC 2026
On Thursday, 1 January 2026 at 17:01:25 UTC, zhade wrote:
> Example:
>
> ```d
> import std.algorithm : filter, map;
> import std.typecons : tuple;
>
> auto example_func(bool fail)
> {
> if (fail)
> {
> // [...]
> }
>
> auto list = someExpensiveOperation();
>
> return list
> .filter!(a => a != "expensive")
> .map!(a => tuple!("value", "numLetters")(a, a.length));
> }
>
> string[] someExpensiveOperation()
> {
> return ["some", "expensive", "operation"];
> }
> ```
You could try something like this:
```d
auto example_func(bool fail)
{
string[] list;
if (fail)
list = [];
else
list = someExpensiveOperation();
return list
.filter!(...)
.map!(...);
}
```
Because `map` and `filter` are lazy, calling them on an empty
`list` won't do anything, but they will still return the correct
type.
More information about the Digitalmars-d-learn
mailing list