因为我过于简单化了其他问题 https://stackoverflow.com/questions/13251388/elegant-haskell-case-error-handling之前,我想在这里举一个更清楚的例子。
如何处理必须按顺序检查某些条件而不嵌套多个情况的情况?对于“顺序方式”,我的意思是获取一个值(例如从标准输入),在特定条件下检查该值,并根据结果获取另一个值,依此类推。
Example:
sequen :: IO String
sequen = do
a <- getLine
case a of
"hi" -> do
putStrLn "hello!"
b <- getLine
case b of
"how are you?" -> do
putStrLn "fine, thanks"
return "nice conversation"
_ -> return "error 2"
_ -> return "error 1"
我知道有更好的方法来编写这样的聊天机器人,它应该只是展示问题的顺序性质。正如您所看到的,对于每个嵌套情况,代码也会缩进得更深。
有没有办法更好地构造这样的代码?我正在考虑在一个地方处理“错误”并描述“成功路径”,而不将错误处理分布在整个地方。
当然。这正是EitherT
是为.你可以从Control.Monad.Trans.Either
in the eitherT
包裹。
import Control.Monad.Trans.Class
import Control.Monad.Trans.Either
main = do
e <- runEitherT $ do
a <- lift getLine
case a of
"hi" -> lift $ putStrLn "hello!"
_ -> left 1
b <- lift getLine
case b of
"how are you?" -> lift $ putStrLn "fine, thanks!"
_ -> left 2
return "nice conversation"
case e of
Left n -> putStrLn $ "Error - Code: " ++ show n
Right str -> putStrLn $ "Success - String: " ++ str
EitherT
每当遇到以下情况时中止当前代码块left
语句,人们通常用它来指示错误情况。
内部块的类型是EitherT Int IO String
。当你runEitherT
它,你得到IO (Either Int String)
. The Left
类型对应于失败的情况left
和Right
value 表示它成功到达块的末尾。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)