Skip to content

Either: Add Map helper function#7

Open
CorentinClabaut wants to merge 1 commit into
samber:masterfrom
CorentinClabaut:eithermap
Open

Either: Add Map helper function#7
CorentinClabaut wants to merge 1 commit into
samber:masterfrom
CorentinClabaut:eithermap

Conversation

@CorentinClabaut

Copy link
Copy Markdown
Contributor

closes #6

@samber

samber commented Aug 8, 2022

Copy link
Copy Markdown
Owner

Hi @CorentinClabaut

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

@CorentinClabaut

Copy link
Copy Markdown
Contributor Author

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

Copy link
Copy Markdown
Contributor Author

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.

@samber

samber commented Sep 2, 2022

Copy link
Copy Markdown
Owner

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? 🤔

@CorentinClabaut

Copy link
Copy Markdown
Contributor Author

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

What about creating multiple functions MapOption, MapResult, MapEitherX ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants