Return explicitly "empty" MapResult (fail-fast)

kdevel kdevel at vogtner.de
Fri Jan 30 00:28:53 UTC 2026


On Thursday, 29 January 2026 at 20:44:17 UTC, Ali Çehreli wrote:
> On 1/28/26 12:37 AM, kdevel wrote:
>> On Tuesday, 27 January 2026 at 02:05:45 UTC, Ali Çehreli wrote:
[...]
>>> auto example_func(bool fail)
>>> {
>>>     alias filterFunc = a => a != "expensive";
>>>     alias mapFunc = a => tuple!("value", "numLetters")(a, 
>>> a.length);
>>>
>>>     auto makeRange(R)(R r = 
>>> typeof(someExpensiveOperation()).init) {
>>>         return r
>>>             .filter!filterFunc
>>>             .map!mapFunc;
>>>     }
>>>
>>>     if (fail)
>>>     {
>>>         return makeRange();
>>>     }
>>>
>>>     auto list = someExpensiveOperation();
>>>
>>>     return makeRange(list);
>>> }

Your function is equivalent to

    auto example_func (bool fail)
    {
       alias filterFunc = a => a != "expensive";
       alias mapFunc = a => tuple!("value", "numLetters")(a, 
a.length);

       auto list = fail
          ? typeof(someExpensiveOperation()).init
          : someExpensiveOperation();

       return list
          .filter!filterFunc
          .map!mapFunc;
    }

but it has only two levels of indentation and no nested function 
(template). Alas it shares the duplication of 
"someExpensiveOperation()".

>>> makeRange need not be a template but the code is a little 
>>> cleaner when
>>> it is.
>>
>> Would it not be even cleaner with less indentation, less ifs 
>> and less
>> functions?:
>
> Not always because not all complex range objects can be 
> assigned 'null'.
>
>>        auto list = fail
>>           ? null // []
>>           : someExpensiveOperation();
>
> That does not work in the general case.

Use `typeof(someExpensiveOperation()).init` instead of `null` in 
whatever general case you suggest.

>> BTW: The OP mentioned the notion of "fail fast". example_func 
>> is not
>> fail fast.
>
> I must have misunderstood but it fails fast because it does 
> nothing at all before returning the empty result. (The OP's 
> goal.)

Maybe the OP favors a different definition of "fail fast" as the 
function under close scrutiny is not failing at all.

       FailFast also refers to some programming techniques that 
cause
       an exception to be thrown or other redirection of control to
       occur upon meeting certain conditions. [...]

       http://c2.com/


More information about the Digitalmars-d-learn mailing list