如何在Haskell中将此功能从ExceptT转换为Except?

问题描述 投票:2回答:2

我对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"
haskell exception monad-transformers
2个回答
2
投票

badFunction应该是ExceptT Error IO ()的原因是因为runExceptT具有类型runExceptT :: ExceptT e m a -> m (Either e a)。由于您的主机的类型为runExceptT :: ExceptT e m a -> m (Either e a),因此这意味着main :: IO ()必须为runExceptT badFunction,因此IO …中的m应该为ExceptT e m a

但是您本身不需要此,您的IO不执行任何badFunction,因此您可以将其定义为IO

Except

然后您可以通过使用badFunction :: Except Error () badFunction = throwE Empty从标识中获取值,然后在IO ()中使用它,然后使用runIdentitypure中“ wrap”结果:]]

IO

但是我们只能在main :: IO () main = do caught_result <- pure (runIdentity (runExceptT badFunction)) case caught_result of Left _ -> putStrLn "caught some error" Right _ -> putStrLn "no errors were caught"中使用let …子句并删除main

pure

作为main :: IO () main = do let caught_result = runIdentity (runExceptT badFunction) case caught_result of Left _ -> putStrLn "caught some error" Right _ -> putStrLn "no errors were caught"@JonPurdy saysrunIdentity的组合为runExceptT,因此我们可以将其重写为:

runExcept :: Except e a -> Either e a    

0
投票

您写

© www.soinside.com 2019 - 2024. All rights reserved.