[英]Why pattern matching does not throw exception in Maybe monad
我的问题很简单。 为什么错误的模式匹配不会在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
看看tryConstuctHTTPTask函数。 我认为当模式不匹配时(例如“ Object getP ”)我们必须得到类似“ Prelude.Exception ”的东西,而不是我得到的“ Nothing ”。 我喜欢这种行为,但我不明白为什么。
谢谢。
在do
-block中执行pattern <- expression
,当模式不匹配时将调用fail
。 所以它等同于做
expression >>= \x ->
case x of
pattern -> ...
_ -> fail
由于在Maybe
monad中将fail
定义为Nothing
,因此使用<-
来获取失败模式匹配的Nothing
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.