{-# LANGUAGE CPP #-}
{-# LANGUAGE Safe #-}
{-# LANGUAGE NoImplicitPrelude #-}

module Protolude.Either (
  maybeToLeft
, maybeToRight
, leftToMaybe
, rightToMaybe
, maybeEmpty
, maybeToEither
, fromLeft
, fromRight
) where

import Data.Function (const)
import Data.Monoid (Monoid, mempty)
import Data.Maybe (Maybe(Nothing, Just), maybe)
import Data.Either (Either(Left, Right), either)
#if MIN_VERSION_base(4,10,0)
import Data.Either (fromLeft, fromRight)
#else
-- | Return the contents of a 'Right'-value or a default value otherwise.
fromLeft :: a -> Either a b -> a
fromLeft _ (Left a) = a
fromLeft a _        = a

-- | Return the contents of a 'Right'-value or a default value otherwise.
fromRight :: b -> Either a b -> b
fromRight _ (Right b) = b
fromRight b _         = b
#endif

leftToMaybe :: Either l r -> Maybe l
leftToMaybe :: forall l r. Either l r -> Maybe l
leftToMaybe = forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either forall a. a -> Maybe a
Just (forall a b. a -> b -> a
const forall a. Maybe a
Nothing)

rightToMaybe :: Either l r -> Maybe r
rightToMaybe :: forall l r. Either l r -> Maybe r
rightToMaybe = forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either (forall a b. a -> b -> a
const forall a. Maybe a
Nothing) forall a. a -> Maybe a
Just

maybeToRight :: l -> Maybe r -> Either l r
maybeToRight :: forall l r. l -> Maybe r -> Either l r
maybeToRight l
l = forall b a. b -> (a -> b) -> Maybe a -> b
maybe (forall a b. a -> Either a b
Left l
l) forall a b. b -> Either a b
Right

maybeToLeft :: r -> Maybe l -> Either l r
maybeToLeft :: forall r l. r -> Maybe l -> Either l r
maybeToLeft r
r = forall b a. b -> (a -> b) -> Maybe a -> b
maybe (forall a b. b -> Either a b
Right r
r) forall a b. a -> Either a b
Left

maybeEmpty :: Monoid b => (a -> b) -> Maybe a -> b
maybeEmpty :: forall b a. Monoid b => (a -> b) -> Maybe a -> b
maybeEmpty = forall b a. b -> (a -> b) -> Maybe a -> b
maybe forall a. Monoid a => a
mempty

maybeToEither :: e -> Maybe a -> Either e a
maybeToEither :: forall l r. l -> Maybe r -> Either l r
maybeToEither e
e Maybe a
Nothing = forall a b. a -> Either a b
Left e
e
maybeToEither e
_ (Just a
a) = forall a b. b -> Either a b
Right a
a