我对 Except
很困惑,特别是因为网络上没有好的教程。我不知道如何将此函数从 ExceptT
转换为 Except
:
data Error = Empty deriving (Show)
badFunction :: ExceptT Error IO ()
badFunction = throwError Empty
main :: IO ()
main = do
caught_result <- runExceptT badFunction
case caught_result of
Left _ -> putStrLn "caught some error"
Right _ -> putStrLn "no errors were caught"
最佳答案
badFunction
应该是 ExceptT Error IO ()
的原因是因为 runExceptT
的类型为 runExceptT :: ExceptT e m a -> m (Either e a)
.由于您的 main 类型为 main::IO ()
,这意味着 runExceptT badFunction
需要为 IO …
,因此 m
应该是ExceptT e m a
中的IO
。
但你本身并不需要这个,你的 badFunction
不做任何 IO
,所以你可以将它定义为一个 Except
:
badFunction :: <b>Except</b> Error ()
badFunction = throwE Empty
然后可以在IO()
中使用runIdentity
从identity中获取值,然后使用pure
将结果“包装”到 IO
中:
main :: IO ()
main = do
caught_result <- pure (<b>runIdentity</b> (runExceptT badFunction))
case caught_result of
Left _ -> putStrLn "caught some error"
Right _ -> putStrLn "no errors were caught"
但是我们可以在 main
中使用 let …
子句并删除 pure
:
main :: IO ()
main = do
let caught_result = <b>runIdentity</b> (runExceptT badFunction)
case caught_result of
Left _ -> putStrLn "caught some error"
Right _ -> putStrLn "no errors were caught"
作为@JonPurdy says , runIdentity
和 runExceptT
的组合是 runExcept :: Except e a -> Either e a
,所以我们可以将其重写为:
main :: IO ()
main = do
let caught_result = <b>runExcept</b> badFunction
case caught_result of
Left _ -> putStrLn "caught some error"
Right _ -> putStrLn "no errors were caught"
关于haskell - 如何将此函数从 ExceptT 转换为 Haskell 中的 Except?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62290526/