darcs patch: Add justIf to Data.Maybe

Duncan Coutts duncan.coutts at worc.ox.ac.uk
Sat Aug 22 11:10:37 EDT 2009

On Sat, 2009-08-22 at 10:18 +0200, Joachim Breitner wrote:
> Hi,
> I propose the attached change

> Fri Aug 21 19:17:12 CEST 2009  Joachim Breitner <mail at joachim-breitner.de>
>   * Add justIf to Data.Maybe

justIf :: a -> Bool -> Maybe a
justIf x True = Just x
justIf x False = Nothing

Which apparently is intended to be used like:

v `justIf` a

Another instance of this idiom, this one from Cabal, is

check :: Bool -> PackageCheck -> Maybe PackageCheck
check False _  = Nothing
check True  pc = Just pc

which generalises to

check :: Bool -> a -> Maybe a
check False _  = Nothing
check True  x  = Just x

which is used without `back ticks` like:

check (not (null deprecatedExtensions)) $
      PackageDistSuspicious $
           "Deprecated extensions: "
        ++ {- some fairly big expression -}

In this use case the result is typically a lot bigger than the
condition, so the condition goes first rather than last.

As Jón was suggesting we might want to generalise to MonadPlus rather
than putting it in Data.Maybe, it becomes rather similar to the existing
function 'guard':

guard :: MonadPlus m => Bool -> m ()
guard True  = return ()
guard False = mzero

check :: MonadPlus m => Bool -> a -> m a
check True  x  = return x
check False _  = mzero

Using a Bool for the condition is a tad more general than a predicate

check :: MonadPlus m => (a -> Bool) -> a -> m a

In particular, the use case in Cabal does not fit the predicate pattern
because the condition is not a condition on the value being returned but
on something else in the environment.

BTW, I also don't want to take too strong a position on the name ;-)


More information about the Libraries mailing list