Mapping over Either's Left

We have such a function in the standard libraries,

Control.Arrow.left :: a b c -> a (Either b d) (Either c d)

is the generalisation to arbitrary Arrows. Substitute (->) for a and apply it infix, to get the specialisation

left :: (b -> c) -> Either b d -> Either c d

There is nothing wrong with your approach in principle, it's a sensible way to handle the situation.


Another option is to use Bifunctor instance of Either. Then you have

first :: (a -> b) -> Either a c -> Either b c

(Also Bifunctor can be used to traverse over the first part of (a,b).)


This can be done easily with lens:

import Control.Lens

over _Left (+1) $ Left 10   => Left 11
over _Left (+1) $ Right 10  => Right 10
over _Right (+1) $ Right 10 => Right 11

Tags:

Haskell

Either