How to chain the use of maybe argument in haskell?

前端 未结 5 1730
渐次进展
渐次进展 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:33

    You could avoid using a Maybe for the title and do:

    greeting :: Bool-> Maybe String -> String
    greeting title name = "Hello" ++ title' ++ (maybe "" id name)
      where title' = if title then "Mr" else ""
    

    If you have a number of Maybes you could use mconcat since String is a monoid:

    import Data.Monoid
    import Data.Maybe
    
    greeting :: [Maybe String] -> String
    greeting l = fromJust $ mconcat ((Just "Hello"):l)
    

提交回复
热议问题