How to chain the use of maybe argument in haskell?

前端 未结 5 1752
渐次进展
渐次进展 2021-01-16 09:06

I\'m trying to build a string from optional arguments. For example to generate a greeting string from a title and a name This is trivial in a imperative language and would l

5条回答
  •  长发绾君心
    2021-01-16 09:35

    Actually Haskell is smarter than any imperative approach.

    Let's imagine name has a value Nothing. Does it make sense to render something like "Hello Mr"? Probably it would make more sense to consider it as an exceptional situation, and for that we can again use Maybe. So first of all, I'd update the signature of the function to the following:

    greeting :: Bool -> Maybe String -> Maybe String
    

    Now we can look at our problem again and find out that Haskell provides multiple ways to approach it.

    Hello, Monads

    Maybe is a monad, so we can use the do syntax with it:

    greeting mr name = do
      nameValue <- name
      return $ if mr
        then "Hello, Mr. " ++ nameValue
        else "Hello, " ++ nameValue
    

    Hello, Functors

    Maybe is also a functor, so alternatively we can use fmap:

    greeting mr name = 
      if mr
        then fmap ("Hello, Mr. " ++) name
        else fmap ("Hello, " ++) name
    

    We can also do a bit of refactoring, if we consider the signature as the following:

    greeting :: Bool -> (Maybe String -> Maybe String)
    

    i.e., as a function of one argument, which returns another function. So the implementaion:

    greeting mr = 
      if mr
        then fmap ("Hello, Mr. " ++)
        else fmap ("Hello, " ++)
    

    or

    greeting True  = fmap ("Hello, Mr. " ++)
    greeting False = fmap ("Hello " ++)
    

    if you find this syntax better.

提交回复
热议问题