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