guard -package:relude

Conditional failure of Alternative computations. Defined by
guard True  = pure ()
guard False = empty

Examples

Common uses of guard include conditionally signaling an error in an error monad and conditionally rejecting the current choice in an Alternative-based parser. As an example of signaling an error in the error monad Maybe, consider a safe division function safeDiv x y that returns Nothing when the denominator y is zero and Just (x `div` y) otherwise. For example:
>>> safeDiv 4 0
Nothing
>>> safeDiv 4 2
Just 2
A definition of safeDiv using guards, but not guard:
safeDiv :: Int -> Int -> Maybe Int
safeDiv x y | y /= 0    = Just (x `div` y)
| otherwise = Nothing
A definition of safeDiv using guard and Monad do-notation:
safeDiv :: Int -> Int -> Maybe Int
safeDiv x y = do
guard (y /= 0)
return (x `div` y)
Conditional failure of Alternative computations. Defined by
guard True  = pure ()
guard False = empty

Examples

Common uses of guard include conditionally signaling an error in an error monad and conditionally rejecting the current choice in an Alternative-based parser. As an example of signaling an error in the error monad Maybe, consider a safe division function safeDiv x y that returns Nothing when the denominator y is zero and Just (x `div` y) otherwise. For example:
>>> safeDiv 4 0
Nothing
>>> safeDiv 4 2
Just 2
A definition of safeDiv using guards, but not guard:
safeDiv :: Int -> Int -> Maybe Int
safeDiv x y | y /= 0    = Just (x `div` y)
| otherwise = Nothing
A definition of safeDiv using guard and Monad do-notation:
safeDiv :: Int -> Int -> Maybe Int
safeDiv x y = do
guard (y /= 0)
return (x `div` y)
Conditional failure, returning only if the condition is True.
Generalization of guard
This module contains monadic predicates.
Succeed only if the extension is disabled.
Succeed only if the extension is enabled.
g `guards` f : when the predicate g holds, f is applied, else none
like whenP
Guard using an arbitrary function on the Request.
Interior editing: g guards f applies f only when the predicate g succeeds, otherwise the content is discarded.
Monadic version of guard. Occasionally useful. Here some complex but real-life example:
findSomePath :: IO (Maybe FilePath)

somePath :: MaybeT IO FilePath
somePath = do
path <- MaybeT findSomePath
guardM $ liftIO $ doesDirectoryExist path
return path