{-# LANGUAGE Safe #-}
module Data.Either.Utils
(
maybeToEither,
forceEither,
forceEitherMsg,
eitherToMonadError,
fromLeft, fromRight, fromEither
) where
import Control.Monad.Except ( MonadError(..) )
maybeToEither :: MonadError e m =>
e
-> Maybe a
-> m a
maybeToEither :: forall e (m :: * -> *) a. MonadError e m => e -> Maybe a -> m a
maybeToEither e
errorval Maybe a
Nothing = e -> m a
forall a. e -> m a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError e
errorval
maybeToEither e
_ (Just a
normalval) = a -> m a
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
normalval
forceEither :: Show e => Either e a -> a
forceEither :: forall e a. Show e => Either e a -> a
forceEither (Left e
x) = [Char] -> a
forall a. HasCallStack => [Char] -> a
error (e -> [Char]
forall a. Show a => a -> [Char]
show e
x)
forceEither (Right a
x) = a
x
forceEitherMsg :: Show e => String -> Either e a -> a
forceEitherMsg :: forall e a. Show e => [Char] -> Either e a -> a
forceEitherMsg [Char]
msg (Left e
x) = [Char] -> a
forall a. HasCallStack => [Char] -> a
error ([Char] -> a) -> [Char] -> a
forall a b. (a -> b) -> a -> b
$ [Char]
msg [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
": " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ e -> [Char]
forall a. Show a => a -> [Char]
show e
x
forceEitherMsg [Char]
_ (Right a
x) = a
x
eitherToMonadError :: MonadError e m => Either e a -> m a
eitherToMonadError :: forall e (m :: * -> *) a. MonadError e m => Either e a -> m a
eitherToMonadError (Left e
x) = e -> m a
forall a. e -> m a
forall e (m :: * -> *) a. MonadError e m => e -> m a
throwError e
x
eitherToMonadError (Right a
x) = a -> m a
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
x
fromLeft :: Either a b -> a
fromLeft :: forall a b. Either a b -> a
fromLeft (Left a
a) = a
a
fromLeft Either a b
_ = [Char] -> a
forall a. HasCallStack => [Char] -> a
error [Char]
"Data.Either.Utils.fromLeft: Right"
fromRight :: Either a b -> b
fromRight :: forall a b. Either a b -> b
fromRight (Right b
a) = b
a
fromRight Either a b
_ = [Char] -> b
forall a. HasCallStack => [Char] -> a
error [Char]
"Data.Either.Utils.fromRight: Left"
fromEither :: Either a a -> a
fromEither :: forall a. Either a a -> a
fromEither (Left a
a) = a
a
fromEither (Right a
a) = a
a