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
I think that your function is violating the SRP (Single responsibility principle). It is doing two things:
Mr
You can notice that the Bool
and String
(name) refer to the same "entity" (a person).
So let's define a person:
data Person
= Mister String
| Person String
deriving (Eq)
We can now create an instance of show
that makes sense:
instance Show Person where
show (Mister name) = "Mr. " ++ name
show (Person name) = name
and finally we can reformulate your greeting function as:
greeting :: Maybe Person -> String
greeting (Just person) = "Hello, " ++ show person
greeting Nothing = "Hello"
Live demo
The code is simple, readable and just few lines longer (don't be afraid of writing code). The two actions (prefixing and greeting) are separated and everything is much simpler.
If you really have to, you can trivially create a function to generate a Mister
or a Person
based on a boolean value:
makePerson :: Bool -> String -> Person
makePerson True = Mister
makePerson False = Person
Live demo