Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 542
user101 Avatar asked Sep 17 '11 09:09

user101


People also ask

Is the shorter the code the better?

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.

How long is a line of code?

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.


1 Answers

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
like image 192
Landei Avatar answered Oct 31 '22 08:10

Landei