如何阻止 Maybe 被传递到 Haskell 中的另一个函数

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

我已经看过 this 答案,但我不清楚如何在我的情况下应用它。

我有以下功能:

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

getName 函数将 CDef 作为参数。但是上面的代码将无法运行并出现以下错误:

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

我试过了:

designC UnknownString c = getName (Just c)

但错误表明这让事情变得更糟

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

如何只将 CDef 传递给 getName?

你必须处理你的 Maybe 什么都不是的情况。

要么提供一些默认值

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

或者抛出异常

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