haskell - 如何将此函数从 ExceptT 转换为 Haskell 中的 Except?

标签 haskell exception monad-transformers

我对 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 , runIdentityrunExceptT 的组合是 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/

相关文章:

regex - 区分 Haskell 中的空正则表达式匹配和无匹配

haskell - 如何设置使用 Stack 构建的 Haskell 项目的可执行输出位置?

haskell - RankNTypes 和教堂数字

haskell - 在 Happstack 请求处理程序中捕获程序错误

haskell - 如何结合数据组合和 monad 转换器

objective-c - Objective c 类扩展 header - xcode 中的新功能

iOS CALayerInvalidGeometry

java - 检查网格,抛出越界异常

Haskell 将不确定性与错误处理相结合

haskell - 在 monad 转换器中,为什么已知的 monad 是内部的?