0

I have two functions that return Either<Error,?>, and the 2nd function depends on the first one.

Either<Error, bool> either1 = ReturnEither1(...);
Either<Error, int> either2 = either1.Bind(ReturnEither2);

Now, I have a 3rd function which depends on both either1 and either2 and its left type is also Error. How can I do something like below?


Either<Error, MyType> either3 = [either1, either2].BindAll(...);

So I want either3 to bind to the right of both either1 and either2.

David S.
  • 10,578
  • 12
  • 62
  • 104
  • How does `Either` look like? Maybe you can use self-referencing generic constraint – Pavel Anikhouski May 06 '20 at 07:11
  • 1
    I don't know csharp syntax, but you usually nest bind calls `either1.Bind((x) => either2.Bind((y) => ReturnEither3(x, y))`. –  May 06 '20 at 07:36
  • @bob, in my case it is a combination of `bind` and `map`. Thanks! Would you convert this into an answer? – David S. May 06 '20 at 07:46

1 Answers1

2

You cannot have some BindAll easily because you will lose type safety (MyType vs. individual return types). I guess you could build something using Fold on the enumeration of functions if you really think you need something that way.

For what you want I prefer LINQ syntax in C#:

var result = from x1 in ReturnEither1()
             from x2 in ReturnEither2(x1)
             from x3 in ReturnEither3(x1, x2) // you can use any of the previous results
             select x3;

This will call SelectMany on the monadic type which is Bind (see documentation of LanguageExt). You get a right value if every function returns right -- otherwise, get the first left value (first error).

Result will be of Either type like return value of ReturnEither3. All individual functions (ReturnEither*) need same left type, but can have different right type.

David S.
  • 10,578
  • 12
  • 62
  • 104
stb
  • 772
  • 5
  • 15