Is there a standard function for "do this if just x"?
I have the following code:
doIf :: (a -> IO ()) -> Maybe a -> IO () doIf fx = case x of Just i -> fi Nothing -> return () main = do mapM_ (doIf print) [Just 3, Nothing, Just 4] which outputs:
3 4 In other words, Just values ββprint, but Nothing causes no action. (And don't interrupt the calculations.)
Is there such a standard feature in Haskell libraries? Also, could this be more general? I tried replacing IO () with mb , but then return () does not work. How do you write return () for any monad? (If possible ..) Could Maybe be generalized here?
Finally, can I completely remove the doIf function? Can I have a <#> operator that applies an argument if Nothing ?
print <#> Just 3 print <#> Nothing displays
3 But I do not know if this is possible.
Your doIf is a special case of Data.Foldable.traverse_ .
You can usually find such a thing through Hoogle , but it seems to be a bit broken at the moment. The command line version that I installed on my system gives Data.Foldable.traverse_ as the first result for the query (a -> IO ()) -> Maybe a -> IO () .
And of course, you can define this statement simply (<#>) = doIf (or (<#>) = Data.Foldable.traverse_ ).