Hi, I am trying to fail-fast and need to return "something" that works together with MapResult.

I came up with a solution but wanted to know if its the supposed way to do it.

What I learned is that the lambdas of `map` and `filter` are part of the return type.

Example:

```d
import std.algorithm : filter, map;
import std.typecons : tuple;

auto example_func(bool fail)
{
    if (fail)
    {
        return []; // empty result. What to return here?
// Error: expected return type of `void[]`, not `MapResult! // (__lambda_L34_C15, FilterResult!(__lambda_L33_C18, string[]))`

        return [].map!(a => a);
// Error: template `map` is not callable using argument types `!()(void[])`

return (cast(string[])[].map!(a => tuple!("value", "numLetters")("", 0)); // Error: expected return type of `MapResult!(__lambda_L34_C40, string[])`, not `MapResult!(__lambda_L41_C15, FilterResult!(__lambda_L40_C18, string[]))`

return (cast(string[])[]).filter!(a => a != "expensive").map!(a => tuple!("value", "numLetters")("", 0)); // Error: expected return type of `MapResult!(__lambda_L34_C59, FilterResult!(__lambda_L34_C43, string[]))`, not `MapResult!(__lambda_L41_C15, FilterResult!(__lambda_L40_C18, string[]))`
    }

    auto list = someExpensiveOperation();

    return list
        .filter!(a => a != "expensive")
        .map!(a => tuple!("value", "numLetters")(a, a.length));
}

string[] someExpensiveOperation()
{
    return ["some", "expensive", "operation"];
}
```

With that I gathered that there is no other way but to use another function which solely applies the `map` and `filter`?

This works:

```d
auto example_func(bool fail)
{
    if (fail)
    {
        return transform([]);
    }

    auto list = someExpensiveOperation();

    return transform(list);
}

auto transform(string[] input)
{
    return input
        .filter!(a => a != "expensive")
        .map!(a => tuple!("value", "numLetters")(a, a.length));
}
```

Is this the supposed way to do it?

Reply via email to