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
Efficiency Arguably, using shorter lines of code is more efficient than spreading the code over several lines. If you have more lines of code, there are more places for bugs to hide and finding them might be more of a hassle.
Ideally, one line of code is a unit element that means or performs something specific – a part of a sentence if you will. It is generally agreed that the ideal length for a line of code is from 80 to 100 characters.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With