packages feed

antelude-0.1.0: src/Antelude/Maybe.hs

{- |
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 = fmap


-- | Get the contents of a 'Maybe', using a default if 'Nothing'.
withDefault :: a -> Maybe a -> a
withDefault = 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 = 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 = \case
  Ok ok -> Just ok
  Err _ -> 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 = \case
  Right right -> Just right
  Left _ -> 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 = \case
  Left left -> Just left
  Right _ -> Nothing