我对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)
。由于您的主机的类型为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 ()
中使用它,然后使用runIdentity
在pure
中“ 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 says和runIdentity
的组合为runExceptT
,因此我们可以将其重写为:
runExcept :: Except e a -> Either e a
您写