I have a function that returns an Either. On finding a Left return I'd like to substitute in some default object and process that. What's the appropriate pattern, using Language Ext, for doing so?
There's a model for this below - myfunc returns an Either, and if it returns a TestFail I'd like to substitute in an empty string[] and process that. The following is ugly -- it checks null and relies on implicit conversion of Either to EitherData by let:
using System.Linq;
using LanguageExt;
// Call with true or false to explore each branch ...
public void Sandbox(bool succeed)
{
Either<TestFail, string[]> myFunc(bool shouldSucceed)
{
if (shouldSucceed)
{
return new[] {"hello", "world"};
}
return new TestFail("i was doomed.");
}
var x =
from response in myFunc(succeed)
let failures = response.Left
let strings = response.Right
from str in failures != null
? new string[0] // if myFunc failed, just process nothing/null obj
: strings
select "x" + str;
}
with a simple TestFail class:
public class TestFail
{
public string Reason { get; }
public TestFail(string reason)
{
Reason = reason;
}
}
Two things: 1. the implicit cast of a single Either to IEnumerable exposes Left and Right directly without all the safeties of the Either -- is that intentional. 2. what's the nicer way of handling a failure from myfunc?
The smell is that I'm not interested in an Either from myfunc. If I have control of it, I should probably just swallow problems within it and make sure I return the default on failure. If I don't have control of it, however - what to do?