How to avoid checking empty value in Haskell?

I am trying to understand how Haskell programs can avoid testing for "null". I try my best to get rid of the 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 crude understanding is that I have to use a monad transformer so that I can use a single mappend for the Maybe parameter in IO monad, and the do syntax should support it. How can I achieve this?

+4
source share
2 answers

Use forM_ from Data.Foldable , which has the following type:

 forM_ :: (Monad m, Foldable t) => ta -> (a -> mb) -> m () 

Maybe implements the Foldable class, which behaves like a list with zero or one element, so when you specialize t in the above signature of type Maybe , you get:

 forM_ :: (Monad m) => Maybe a -> (a -> mb) -> m () 

You use it as follows:

 forM_ maybeUri $ \uri -> download uri outputPath 

It will only perform an action if the Maybe value is Just .

+9
source

You can use Data.Maybe.maybe (it is also in foreplay, so import is not needed):

 main = do url:outputPath:[] <- getArgs let maybeUri = parseURI url maybe (return ()) (\uri -> download uri outputPath) maybeUri -- The above can also be written as: -- maybe (return ()) ((flip download) outputPath) maybeUri 

maybe accepts:

  • function to run in case of Nothing : here (return ())
  • function to run inside the value: here (\uri -> download uri outputPath)
  • maybe value: maybeUri

I show an alternative way to express a function by the value of Just , using a partially applied function.

I would argue using maybe because it makes it explicit, without having to write out the case expression, that you are dealing with maybe .

0
source

Source: https://habr.com/ru/post/1502111/


All Articles