It is not possible to do this in a monadic chain.
Note that this isn't really concerned with Monad
at all: you're not in any way binding a nested monadic action in the Left
argument or something like that, but you're only transforming the argument itself. It's basically the functor operation fmap
, but on the Left instead of Right part:
fmap :: (r->ρ) -> Either l r -> Either l ρ
fmapLeft :: (l->λ) -> Either l r -> Either λ r
A function with that particular signature, surprisingly, doesn't seem to exist. However, this idea of a functor with two covariant arguments is obviously more general than just Either
, and indeed there's a dedicated class. It has (IMO rather unfortunate naming, clashes with Arrow
)
Data.Bifunctor.first :: (a -> b) -> p a c -> p b c
which specialises in fact to
first :: (a -> b) -> Either a c -> Either b c
So you can use
f :: (Show a) => (Either a b) -> (Either String b)
f = first show