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
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
You can use
guard
to achieve this behavior:This is such a generally useful behavior that I've even defined
ensure
in my own little suite of code for one-offs (everybody has such a thing, right? ;-):Usually I'm a big fan of very generic code, but I actually find this exact function useful often enough, specialized to
Maybe
, that I keep it around instead of usingguard
,mfilter
, and the like.The name I use for it is
justIf
, and I'd typically use it for doing things like this:Basically, stuff where some sort of element-wise filtering or checking needs to be done in a compound expression, so
Maybe
is used to indicate the result of the predicate.For the specialized version like this, there really isn't much you can do to make it shorter. It's already pretty simple. There's a fine line between being concise, and just golfing your code for character count, and for something this simple I wouldn't really worry about trying to "improve" it...
Hm... You are looking for a combinator that takes an
a
, a functiona -> Bool
and returns aMaybe a
. Stop! Hoogle time. There is no complete match, butfind
is quite close:I doubt that you can actually find your function somewhere. But why not define it by yourself?
Use:
from Data.Bool.HT.
You're looking for
mfilter
inControl.Monad
:Note that if the condition doesn't depend on the content of the
MonadPlus
, you can write instead:Given the above definition, you can simply write:
Of course this is no different than Daniel Wagner's
ensure
or FUZxxl'sifMaybe
. But it's name is simplyf
, making it the shortest, and it's definition is precisely the code you gave, making it the most easily proven correct. ;)Some ghci, just for fun
If you couldn't tell, this isn't a very serious answer. The others are a bit more insightful, but I couldn't resist the tongue-in-cheek response to "make this code shorter".