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
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!