I'm trying to grasp how Haskell programs can avoid testing for "empty value". I am struggling to get rid of case expression in this program:
main = do url:outputPath:[] <- getArgs
let maybeUri = parseURI url
case maybeUri of
Just uri -> download uri outputPath
Nothing -> return ()
My very rough understanding is that I should use monad transformer so that I can use single mappend
on Maybe value within IO monad and 'do' syntax should be able to support it. How can I achieve this?
Use forM_
from Data.Foldable
, which has the following type:
forM_ :: (Monad m, Foldable t) => t a -> (a -> m b) -> m ()
Maybe
implements the Foldable
class, behaving like a list with zero or one elements, so when you specialize the t
in the above type signature to Maybe
you get:
forM_ :: (Monad m) => Maybe a -> (a -> m b) -> m ()
You use it like this:
forM_ maybeUri $ \uri -> download uri outputPath
It will only run the action if the Maybe
value turns out to be a Just
.
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