Question

Lets say I have function

(>>*=) :: (Show e') => Either e' a -> (a -> Either e b) -> Either e b

which is converting errors of different types in clean streamlined functions. I am pretty happy about this.

BUT

Could there possibly be function <*- that would do similar job insted of <- keyword, that it would not look too disturbing?

Was it helpful?

Solution 2

It is not possible to write a function that you can use instead of the <- in do notation. The reason is that to the left of <-, there is a pattern, but functions take values. But maybe you can write a function

foo :: (Show e') => Either e' a -> Either e a

that converts the error messages and then use it like this:

do  x <- foo $ code that creates e1 errors
    y <- foo $ code that creates e2 errors

While this is not as good as the <*- you're asking for, it should allow you to use do notation.

OTHER TIPS

Well, my answer is really the same as Toxaris' suggestion of a foo :: Either e a -> Either e' a function, but I'll try to motivate it a bit more.

A function like foo is what we call a monad morphism: a natural transformation from one monad into another one. You can informally think of this as a function that sends any action in the source monad (irrespective of result type) to a "sensible" counterpart in the target monad. (The "sensible" bit is where it gets mathy, so I'll skip those details...)

Monad morphisms are a more fundamental concept here than your suggested >>*= function for handling this sort of situation in Haskell. Your >>*= is well-behaved if it's equivalent to the following:

(>>*=) :: Monad m => n a -> (a -> m b) -> m b
na >>*= k = morph na >>= k
    where 
      -- Must be a monad morphism:
      morph :: n a -> m a
      morph = ...

So it's best to factor your >>*= out into >>= and case-specific monad morphisms. If you read the link from above, and the tutorial for the mmorph library, you'll see examples of generic utility functions that use user-supplied monad morphisms to "edit" monad transformer stacks—for example, use a monad morphism morph :: Error e a -> Error e' a to convert StateT s (ErrorT e IO) a into StateT s (ErrorT e' IO) a.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top