Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Either: Add Map helper function #7

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

CorentinClabaut
Copy link
Contributor

closes #6

@samber
Copy link
Owner

samber commented Aug 8, 2022

Hi @CorentinClabaut

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

@CorentinClabaut
Copy link
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
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
Copy link
Owner

samber commented Sep 2, 2022

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
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
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add Helper function that would work like Either.Match but would return another type
2 participants