Search code examples
haskelloption-type

How to stop Maybe from being passed into another function in Haskell


I have already looked at this answer, but it is unclear to me how to apply it in my situation.

I have the following function:

designC :: DesignC -> Maybe CDef -> String
designC FirstString _ = "first_string"
designC SecondString _ = "second_string"
designC UnknownString c = getName c

The getName function takes a CDef as it's argument. However the above code will not work and has the following error:

No instance for (getIdea (Maybe CDef))     
arising from a use of ‘getName’
In the expression: getName c

I tried:

designC UnknownString c = getName (Just c)

but the error shows that this made things worse

No instance for (getIdea (Maybe (Maybe CDef)))

How can I pass just the CDef to getName?


Solution

  • You have to handle a situation when your Maybe is Nothing.

    Either provide some default value

    defaultValue = ""
    
    designC :: DesignC -> Maybe CDef -> String
    designC FirstString _ = "first_string"
    designC SecondString _ = "second_string"
    designC UnknownString (Just c) = getName c
    designC UnknownString Nothing = defaultValue
    
    -- or shorter
    designC UnknownString c = maybe defaultValue getName c
    

    Or raise an exception

    data MyException = VeryNastyError
    
    designC :: MonadError MyException m => DesignC -> Maybe CDef -> m String
    designC FirstString _ = pure "first_string"
    designC SecondString _ = pure "second_string"
    designC UnknownString (Just c) = pure $ getName c
    designC UnknownString Nothing = throwError VeryNastyError