How to chain the use of maybe argument in haskell?

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

    Haskell is so good at abstractions, it can easily replicate the imperative patterns. What you're doing in your example is called a "builder" pattern. Writer is a monad, which wraps a pattern of accumulation or "building" of any Monoid data, and String is a Monoid.

    import Control.Monad.Writer hiding (forM_)
    import Data.Foldable
    
    greeting :: Bool -> Maybe String -> String -> String
    greeting mr name surname = 
      execWriter $ do
        tell $ "Hello,"
        when mr $ tell $ " Mr."
        forM_ name $ \s -> tell $ " " ++ s
        tell $ " " ++ surname
        tell $ "!"
    
    main = do
      putStrLn $ greeting False (Just "Ray") "Charles"
      putStrLn $ greeting True Nothing "Bean"
    

    Outputs:

    Hello, Ray Charles!
    Hello, Mr. Bean!
    

提交回复
热议问题