I'm searching for something like
liftPredMaybe :: (a -> Bool) -> a -> Maybe a
liftPredMaybe p a
| p a = Just a
| otherwise = Nothing
Is there such a function in Haskell already?
See Question&Answers more detail:osI'm searching for something like
liftPredMaybe :: (a -> Bool) -> a -> Maybe a
liftPredMaybe p a
| p a = Just a
| otherwise = Nothing
Is there such a function in Haskell already?
See Question&Answers more detail:osNot quite a ready-made solution, but with guard
(from Control.Monad
) and (<$)
(from Data.Functor
) we can write:
ensure :: Alternative f => (a -> Bool) -> a -> f a
ensure p a = a <$ guard (p a)
(Thanks to Daniel Wagner for suggesting a nice name for this function.)
A more pointfree spelling of dubious taste is p -> (<$) <*> guard . p
.