Shorter way to write this code
问题 The following pattern appears very frequently in Haskell code. Is there a shorter way to write it? if pred x then Just x else Nothing 回答1: You're looking for mfilter in Control.Monad: mfilter :: MonadPlus m => (a -> Bool) -> m a -> m a -- mfilter odd (Just 1) == Just 1 -- mfilter odd (Just 2) == Nothing Note that if the condition doesn't depend on the content of the MonadPlus , you can write instead: "foo" <$ guard (odd 3) -- Just "foo" "foo" <$ guard (odd 4) -- Nothing 回答2: Hm... You are