How to chain the use of maybe argument in haskell?

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

    I think that your function is violating the SRP (Single responsibility principle). It is doing two things:

    • prefixing the name with Mr
    • rendering the greeting message

    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

提交回复
热议问题