{- |
Module      : Antelude.Maybe
Description : Contains some functions for Maybes.
Maintainer  : dneavesdev@pm.me
-}
module Antelude.Maybe
    ( Maybe (..)
      -- | Reexport from 'Data.Maybe'
    , Maybe.isJust
      -- | Reexport from 'Data.Maybe'
    , Maybe.isNothing
    , fromEitherLeft
    , fromEitherRight
    , fromResult
    , map
    , mapWithDefault
    , withDefault
    ) where

import safe           Antelude.Internal.TypesClasses
    ( Either (..)
    , Functor (fmap)
    , Maybe (..)
    , Result (..)
    )

import safe qualified Data.Maybe                     as Maybe


-- | Defined as 'fmap'. Apply a function to the contents of a 'Maybe', doing nothing if 'Nothing'.
map :: (a -> b) -> Maybe a -> Maybe b
map :: forall a b. (a -> b) -> Maybe a -> Maybe b
map = (a -> b) -> Maybe a -> Maybe b
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap


-- | Get the contents of a 'Maybe', using a default if 'Nothing'.
withDefault :: a -> Maybe a -> a
withDefault :: forall a. a -> Maybe a -> a
withDefault = a -> Maybe a -> a
forall a. a -> Maybe a -> a
Maybe.fromMaybe


-- | A combination of 'map'/'fmap' and 'withDefault'. Given a default, a function, and a 'Maybe', get the mapped contents if 'Just', or the default if 'Nothing'.
mapWithDefault :: b -> (a -> b) -> Maybe a -> b
mapWithDefault :: forall b a. b -> (a -> b) -> Maybe a -> b
mapWithDefault = b -> (a -> b) -> Maybe a -> b
forall b a. b -> (a -> b) -> Maybe a -> b
Maybe.maybe


-- | Convert a 'Result a b' to an 'Maybe a', taking the 'Ok' case, or 'Nothing' in the case of 'Err'.
fromResult :: Result err ok -> Maybe ok
fromResult :: forall err ok. Result err ok -> Maybe ok
fromResult = \case
  Ok ok
ok -> ok -> Maybe ok
forall a. a -> Maybe a
Just ok
ok
  Err err
_ -> Maybe ok
forall a. Maybe a
Nothing


-- | Convert a 'Either a b' to an 'Maybe a', taking the 'Right' case, or 'Nothing' in the case of 'Left'.
fromEitherRight :: Either left right -> Maybe right
fromEitherRight :: forall left right. Either left right -> Maybe right
fromEitherRight = \case
  Right right
right -> right -> Maybe right
forall a. a -> Maybe a
Just right
right
  Left left
_ -> Maybe right
forall a. Maybe a
Nothing


-- | Convert a 'Either a b' to an 'Maybe a', taking the 'Left' case, or 'Nothing' in the case of 'Right'.
fromEitherLeft :: Either left right -> Maybe left
fromEitherLeft :: forall left right. Either left right -> Maybe left
fromEitherLeft = \case
  Left left
left -> left -> Maybe left
forall a. a -> Maybe a
Just left
left
  Right right
_ -> Maybe left
forall a. Maybe a
Nothing