haskellerror-handlingoption-typemonadseither

Either and inner Maybe error handling


Is there a Haskell pattern that obviates the writing of this custom function? The idea being to handle the Nothing from Maybe as an error (as part of the wrapping Either):

eitherMaybeHandle :: String -> Either String (Maybe a) -> Either String a
eitherMaybeHandle err = \case
  Left e ->
    Left e
  Right Nothing ->
    Left err
  Right (Just a) ->
    Right a

Solution

  • First, you can use sequence to turn an Either a (Maybe b) into a Maybe (Either a b). Then you can apply fromMaybe to the result along with your value of type a in order to get an Either a b.

    import Data.Maybe (fromMaybe)
    
    eitherMaybeHandle :: a -> Either a (Maybe b) -> Either a b
    eitherMaybeHandle err = fromMaybe (Left err) . sequence