I have the following code:
doIf :: (a -> IO ()) -> Maybe a -> IO ()
doIf f x = case x of
Just i -> f i
Nothing -> return ()
main = do
mapM_ (doIf print) [Just 3, Nothing, Just 4]
which outputs:
3
4
In other words, the Just
values are printed, but Nothing
values cause no action. (And do not interrupt computation.)
Is there a standard function like this in the Haskell libraries? Also, can this be made more generic? I tried replacing IO ()
with m b
but then return ()
does not work. How do you generically write return ()
for any monad? (If possible..) Can even the Maybe
be generalized here?
Lastly, can I do away with the doIf
function entirely? Can I have an operator <#> that applies an argument unless Nothing
?
print <#> Just 3
print <#> Nothing
would output
3
But I don't know if this is possible.
Take a look at the function:
maybe :: b -> (a -> b) -> Maybe a -> b
You've almost written it in doIf
except for the fixed return ()
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