Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid checking for empty value in Haskell?

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?

like image 858
Rumca Avatar asked Jan 13 '23 09:01

Rumca


1 Answers

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.

like image 134
Gabriella Gonzalez Avatar answered Jan 22 '23 05:01

Gabriella Gonzalez