git-annex/Utility/Monad.hs

84 lines
2 KiB
Haskell
Raw Normal View History

2011-10-16 04:31:25 +00:00
{- monadic stuff
-
- Copyright 2010-2012 Joey Hess <id@joeyh.name>
2011-10-16 04:31:25 +00:00
-
- License: BSD-2-clause
2011-10-16 04:31:25 +00:00
-}
{-# OPTIONS_GHC -fno-warn-tabs #-}
module Utility.Monad (
firstM,
getM,
anyM,
allM,
untilTrue,
ifM,
(<||>),
(<&&>),
observe,
after,
noop,
) where
2011-10-16 04:31:25 +00:00
import Data.Maybe
import Control.Monad
2011-10-16 04:31:25 +00:00
{- Return the first value from a list, if any, satisfying the given
- predicate -}
2012-01-21 06:24:12 +00:00
firstM :: Monad m => (a -> m Bool) -> [a] -> m (Maybe a)
2011-10-16 04:31:25 +00:00
firstM _ [] = return Nothing
firstM p (x:xs) = ifM (p x) (return $ Just x , firstM p xs)
2011-10-16 04:31:25 +00:00
{- Runs the action on values from the list until it succeeds, returning
- its result. -}
getM :: Monad m => (a -> m (Maybe b)) -> [a] -> m (Maybe b)
getM _ [] = return Nothing
getM p (x:xs) = maybe (getM p xs) (return . Just) =<< p x
2012-01-03 22:36:31 +00:00
{- Returns true if any value in the list satisfies the predicate,
2011-10-16 04:31:25 +00:00
- stopping once one is found. -}
2012-01-21 06:24:12 +00:00
anyM :: Monad m => (a -> m Bool) -> [a] -> m Bool
2011-10-16 04:31:25 +00:00
anyM p = liftM isJust . firstM p
2011-12-03 13:10:23 +00:00
allM :: Monad m => (a -> m Bool) -> [a] -> m Bool
allM _ [] = return True
allM p (x:xs) = p x <&&> allM p xs
2011-12-03 13:10:23 +00:00
{- Runs an action on values from a list until it succeeds. -}
2012-01-21 06:24:12 +00:00
untilTrue :: Monad m => [a] -> (a -> m Bool) -> m Bool
2011-12-03 13:10:23 +00:00
untilTrue = flip anyM
2012-01-02 15:01:08 +00:00
{- if with a monadic conditional. -}
ifM :: Monad m => m Bool -> (m a, m a) -> m a
ifM cond (thenclause, elseclause) = do
c <- cond
if c then thenclause else elseclause
{- short-circuiting monadic || -}
(<||>) :: Monad m => m Bool -> m Bool -> m Bool
ma <||> mb = ifM ma ( return True , mb )
{- short-circuiting monadic && -}
(<&&>) :: Monad m => m Bool -> m Bool -> m Bool
ma <&&> mb = ifM ma ( mb , return False )
{- Same fixity as && and || -}
2012-11-02 16:48:52 +00:00
infixr 3 <&&>
infixr 2 <||>
2012-01-03 04:29:27 +00:00
{- Runs an action, passing its value to an observer before returning it. -}
2012-01-21 06:24:12 +00:00
observe :: Monad m => (a -> m b) -> m a -> m a
2012-01-02 15:01:08 +00:00
observe observer a = do
r <- a
_ <- observer r
return r
2012-01-02 18:54:23 +00:00
2012-01-03 04:29:27 +00:00
{- b `after` a runs first a, then b, and returns the value of a -}
2012-01-21 06:24:12 +00:00
after :: Monad m => m b -> m a -> m a
2012-01-03 04:29:27 +00:00
after = observe . const
2012-04-22 03:32:33 +00:00
{- do nothing -}
noop :: Monad m => m ()
noop = return ()