尝试返回Either而不是IO(前一个)

Joe*_*and 1 haskell exception-handling

我正在尝试处理来自请求解析器的异常:

   go bs =                                                                 
       case try $ parseRequest reader bs secure of                             
         Left  ex             -> exceptionHandler writer ex                 
         Right (request, bs') -> do                                         
            sendResponse writer =<< app request                             
            go bs'                                                               
Run Code Online (Sandbox Code Playgroud)

但是在使用时我遇到了一个问题try:

Couldn't match expected type `IO (Either e0 (Request, ByteString))'
            with actual type `Either t0 t1'
In the pattern: Left ex
In a case alternative: Left ex -> exceptionHandler writer ex
In the expression:
  case try $ parseRequest reader bs secure of {
    Left ex -> exceptionHandler writer ex
    Right (request, bs')
      -> do { sendResponse writer =<< app request;
              go bs' } }
Run Code Online (Sandbox Code Playgroud)

IO (Either e0 (Request, ByteString))正是我除了得到的try因为它的类型是try :: Exception e => IO a -> IO (Either e a),但我得到了Either e a.

我错过了什么?

sep*_*p2k 7

try确实产生了IO (Either e a).您收到错误消息是因为您将匹配try模式生成的值与Left ex具有类型的模式匹配,而Either a b不是IO a.

要修复你的代码,你需要EitherIO(使用>>=<-内部do),然后模式匹配.


luq*_*qui 5

在GHC 7.6及更高版本中,您可以使用

try (parseRequest reader bs secure) >>= \case
    Left ex -> ...
    Right (request, bs') -> ...
Run Code Online (Sandbox Code Playgroud)

如果启用 {-# LANGUAGE LambdaCase #-}