Ant*_*ton 8 monads haskell exception
我的问题很简单.为什么错误的模式匹配不会在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
Run Code Online (Sandbox Code Playgroud)
看看tryConstuctHTTPTask函数.我认为当模式不匹配时(例如" Object getP ")我们必须得到类似" Prelude.Exception "的东西,而不是我得到的" Nothing ".我喜欢这种行为,但我不明白为什么.
谢谢.
sep*_*p2k 14
这样做pattern <- expression的do-块,将调用fail时模式不匹配.所以它等同于做
expression >>= \x ->
case x of
pattern -> ...
_ -> fail
Run Code Online (Sandbox Code Playgroud)
由于在monad中fail定义Nothing,因此使用的是失败的模式匹配.MaybeNothing<-
| 归档时间: |
|
| 查看次数: |
595 次 |
| 最近记录: |