-- | Extra functions for dealing with Maybe.

module Data.Maybe.Extra where

import Control.Monad

-- | When the predicate is true, return maybe the action's return value.
whenMaybe :: Monad m => Bool -> m a -> m (Maybe a)
whenMaybe False _ = return Nothing
whenMaybe True m = liftM Just m

-- | When a value is Just, do something with it, monadically.
whenJust :: Monad m => Maybe a -> (a -> m c) -> m ()
whenJust (Just a) m = m a >> return ()
whenJust _         _ = return ()

-- | Return the sole element of the list or nothing.
sole :: [a] -> Maybe a
sole [x] = Just x
sole _   = Nothing