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)?
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?:
auto example_func (bool fail)
{
alias filterFunc = a => a != "expensive";
alias mapFunc = a => tuple!("value", "numLetters")(a,
a.length);
auto list = fail
? null // []
: someExpensiveOperation();
return list
.filter!filterFunc
.map!mapFunc;
}
BTW: The OP mentioned the notion of "fail fast". example_func is
not
fail fast. It fails fast if it immediately throws:
auto example_func (bool fail)
{
enforce (! fail, "oh no, failing...");
alias filterFunc = a => a != "expensive";
alias mapFunc = a => tuple!("value", "numLetters")(a,
a.length);
return someExpensiveOperation()
.filter!filterFunc
.map!mapFunc;
}