{-# LANGUAGE LambdaCase #-}

-- | Utils for Maybe data type
module Haskus.Utils.Maybe
   ( onNothing
   , onNothingM
   , fromMaybeM
   , headMaybe
   , module Data.Maybe
   )
where

import Data.Maybe

-- | Flipped `fromMaybe`
onNothing :: Maybe a -> a -> a
onNothing :: Maybe a -> a -> a
onNothing = (a -> Maybe a -> a) -> Maybe a -> a -> a
forall a b c. (a -> b -> c) -> b -> a -> c
flip a -> Maybe a -> a
forall a. a -> Maybe a -> a
fromMaybe

-- | Flipped `fromMaybeM`
onNothingM :: Monad m => m (Maybe a) -> m a -> m a
onNothingM :: m (Maybe a) -> m a -> m a
onNothingM = (m a -> m (Maybe a) -> m a) -> m (Maybe a) -> m a -> m a
forall a b c. (a -> b -> c) -> b -> a -> c
flip m a -> m (Maybe a) -> m a
forall (m :: * -> *) a. Monad m => m a -> m (Maybe a) -> m a
fromMaybeM

-- | fromMaybe in a Monad
fromMaybeM :: Monad m => m a -> m (Maybe a) -> m a
fromMaybeM :: m a -> m (Maybe a) -> m a
fromMaybeM m a
v m (Maybe a)
f = m (Maybe a)
f m (Maybe a) -> (Maybe a -> m a) -> m a
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
   Maybe a
Nothing -> m a
v
   Just a
x  -> a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
x

-- | Get the head of the list if the latter is not empty
headMaybe :: [a] -> Maybe a
headMaybe :: [a] -> Maybe a
headMaybe []    = Maybe a
forall a. Maybe a
Nothing
headMaybe (a
x:[a]
_) = a -> Maybe a
forall a. a -> Maybe a
Just a
x