module TFHOE.Lib.Control.Monad where

import Control.Applicative (Applicative(..))
import Control.Monad (Monad(..), (=<<), liftM2, liftM3, liftM4, join)
import Data.Bool
import Data.Maybe (Maybe(..), maybe)

-- * 'Monad'ic utilities

-- | Perform some operation on 'Just', given the field inside the 'Just'.
whenJust :: Applicative m => Maybe a -> (a -> m ()) -> m ()
whenJust mg f = maybe (pure ()) f mg

-- | Like 'when', but where the test can be 'Monad'-ic.
whenM :: Monad m => m Bool -> m () -> m ()
whenM b t = ifM b t (return ())

-- | Like 'unless', but where the test can be 'Monad'-ic.
unlessM :: Monad m => m Bool -> m () -> m ()
unlessM b = ifM b (return ())

-- | Like @if@, but where the test can be 'Monad'-ic.
ifM :: Monad m => m Bool -> m a -> m a -> m a
ifM b t f = do b' <- b; if b' then t else f

-- | Like 'liftM' but 'join' the result of the lifted function.
liftMJoin :: Monad m => (a -> m b) -> m a -> m b
liftMJoin = (=<<)

-- | Like 'liftM2' but 'join' the result of the lifted function.
liftM2Join :: Monad m => (a -> b -> m c) -> m a -> m b -> m c
liftM2Join f ma mb = join (liftM2 f ma mb)

-- | Like 'liftM3' but 'join' the result of the lifted function.
liftM3Join :: Monad m => (a -> b -> c -> m d) -> m a -> m b -> m c -> m d
liftM3Join f ma mb mc = join (liftM3 f ma mb mc)

-- | Like 'liftM3' but 'join' the result of the lifted function.
liftM4Join :: Monad m => (a -> b -> c -> d -> m e) -> m a -> m b -> m c -> m d -> m e
liftM4Join f ma mb mc md = join (liftM4 f ma mb mc md)