exception - 为什么模式匹配不会在 Maybe monad 中引发异常

标签 exception haskell monads

我的问题很简单。为什么错误的模式匹配不会在 Maybe monad 中引发异常。为了清楚起见:

data Task = HTTPTask {
 getParams   ::  [B.ByteString],
 postParams  ::  [B.ByteString],
 rawPostData ::  B.ByteString 
}  deriving (Show)

tryConstuctHTTPTask :: B.ByteString -> Maybe Task
tryConstuctHTTPTask str = do
 case decode str of
    Left _  -> fail ""
    Right (Object trie) -> do
        Object getP    <- DT.lookup (pack "getParams")   trie
        Object postP   <- DT.lookup (pack "postParams")  trie
        String rawData <- DT.lookup (pack "rawPostData") trie
        return $ HTTPTask [] [] rawData

tryConstructHTTPTask 功能。我认为当模式不匹配时(例如“Object getP”),我们必须得到类似“Prelude.Exception”的东西,而不是得到“Nothing”。我喜欢这种行为,但我不明白为什么。

谢谢。

最佳答案

pattern <- expressiondo -block,将调用 fail当模式不匹配时。所以相当于做

expression >>= \x ->
case x of
  pattern -> ...
  _ -> fail

由于fail定义为 NothingMaybe monad,你得到 Nothing对于使用 <- 失败的模式匹配.

关于exception - 为什么模式匹配不会在 Maybe monad 中引发异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4058835/

相关文章:

list ->> 运算符——Haskell 中的穷人循环?

haskell - 缩进操作符

wpf - wpf caliburn ComboBox OnSelectionChanged事件异常

java - 为什么要在 Java 中使用异常处理?

java - SimpleMappingExceptionResolver 无法解析 404

haskell - GHCi 中的奇怪行为

haskell - 到底是什么 "-<",无论如何?

testing - 什么时候应该使用 Debug.Assert()?

python - 通过Python中的元素总和查找列表列表的最大值

Haskell 堆栈版本依赖关系