mo icon indicating copy to clipboard operation
mo copied to clipboard

Either: Add Map helper function

Open CorentinClabaut opened this issue 3 years ago • 5 comments

closes #6

CorentinClabaut avatar Aug 05 '22 06:08 CorentinClabaut

Hi @CorentinClabaut

Why do you need a mo.Map() helper, instead of mo.Either[A, B].Match() ?

samber avatar Aug 08 '22 14:08 samber

It is to be able to map the either to a different type.

That's why I added an helper function instead of a new method.

CorentinClabaut avatar Aug 09 '22 08:08 CorentinClabaut

This helper would be helpful for cases like this:

type Authentification struct { mo.Either[BearerToken, BasicAuth] }

func (a Authentification) GetHeader() string {
        mo.Map(a,
		func(token BearerToken) string { return BuildBearerAuthHeader(string(token)) },
		func(cred BasicAuth) string { return BuildBasicAuthHeader(cred.Username, cred.Password)} })

So far what we can do is:

type Authentification struct { mo.Either[BearerToken, BasicAuth] }

func (a Authentification) GetHeader() string {
	if a.IsLeft() {
		return BuildBearerAuthHeader(string(a.MustLeft()))
	} else {
		basicAuth := a.MustRight()
		return BuildBasicAuthHeader(basicAuth.Username, basicAuth.Password)}
	} 
}

Which is less readable, more error prone.

CorentinClabaut avatar Sep 01 '22 08:09 CorentinClabaut

Hi @CorentinClabaut and sorry for the late reply.

I wonder if we could build a proper implementation of monads, with Applicative, Foldable, Traversable...

We must be able to run a Map() on any data structure of this repository.

Any idea how to do that? 🤔

samber avatar Sep 02 '22 09:09 samber

I can't think of a way of doing it with a single function.

What about creating multiple functions MapOption, MapResult, MapEitherX ?

CorentinClabaut avatar Oct 28 '22 12:10 CorentinClabaut