On 1/28/26 12:37 AM, kdevel wrote:
> On Tuesday, 27 January 2026 at 02:05:45 UTC, Ali Çehreli wrote:
>> On 1/1/26 9:01 AM, zhade wrote:
>>> Hi, I am trying to fail-fast and need to return "something" that
>>> works together with MapResult.
>>
>> A method I used in the past is to put the entire range-generating code
>> inside a function that has a default argument (makeRange below):
>
> Why put that code in a /nested/ function (template)?
Nested because in the general case the function depends on local state
like parameters and local variables.
Template because it's easier now and later for the compiler to pick
correct types instead of my hard-coding.
>> 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);
>> }
>
>> 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.
> 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.)
> It fails fast if it immediately throws:
>
> auto example_func (bool fail)
> {
> enforce (! fail, "oh no, failing...");
Sure but that would be a different method, not an empty result.
Ali