DigitecGalaxus / Galaxus.Functional

A package bringing popular functional abstractions (e.g. Option or Result) to C#.
Other
37 stars 12 forks source link

Add a way to convert an Option<T> to an Either<A, T> #42

Open raphaelimahorn opened 1 year ago

raphaelimahorn commented 1 year ago

With Option<T>.ToEither(B) there is a way to convert an Option to an Either with a fallback value. The drawback is, that the Option's value will always be in the A spot and the fallback value in the B spot.

The order of the A, B, (and C) in an Either have no intrinsic semantic meaning. Therefore there exist legitimate cases, where you have an interface, requiring a parameter of type Either<X,Y> that you would like to call from an Option<Y> or an Either<Y,X>.

To achieve this, there are multiple solutions:

  1. Introduce a method e.g. Swap() on Either<TA, TB> returning an Either<TB, TA>
  2. Introduce two methods on an Option<X>: AsA(B valueIfNone) returning an Either<X, B> and AsB(A valueIfNone) returning an Either<A, X>
NoelWidmer commented 1 year ago

Some question to improve my understanding of your proposal:

  1. Would you remove .ToEither() in favour of .ToA() and .ToB()?
  2. Adding .ToA() and .ToB() would not allow you to swap an Either. Would you therefore suggestion to add .Swap() anyways? I read your proposal like we could either add .Swap() or (.ToA() and .ToB()).

Note that the package generally uses the prefix To instead of As which is why I slightly changed the names of the methods compared to your proposal.

raphaelimahorn commented 1 year ago

For 1. I would obsolete ToEither(), since it's a breaking change to remove it. ToEither and ToA are like the same thing. But I have no strong opinion on that. For 2. I too think that are 2 different use cases. So I think a Swap() Method would be a good extension too since we are currently really limited on how to access the value of an Either.