0

除了我遇到的错误,任何关于我所做的事情有多糟糕的提示都将不胜感激。

所以我会粘贴代码,有点;但我认为这基本上是正确的,我只是无法让 forkFinally 进行类型检查......

错误出现在唯一调用 forkFinally 的行上:

Ambiguous type variable `e0' in the constraint:
  (Exception e0) arising from a use of `forkFinally'
Probable fix: add a type signature that fixes these type variable(s)
In a stmt of a 'do' block:
  t <- forkFinally (echoHandler a) (exitPool p)
In the expression:
  do { a <- accept s;
       t <- forkFinally (echoHandler a) (exitPool p);
       atomically
       $ do { p' <- readTVar p;
              writeTVar p (t : p') };
       repeatAccept s p }
In an equation for `repeatAccept':
    repeatAccept s p
      = do { a <- accept s;
             t <- forkFinally (echoHandler a) (exitPool p);
             atomically
             $ do { p' <- readTVar p;
                    .... };
             .... } Failed, modules loaded: none.

这是代码:

type ConnectionHandler = (Handle, HostName, PortNumber) -> IO ()
type Pool = TVar [ThreadId]

runConn = do
  s <- withSocketsDo (listenOn (PortNumber 1234))
  p <- atomically (newTVar ([]::[ThreadId]))
  t <- forkIO (repeatAccept s p)
  repeatUntilExit stdin stdout putChar ""
  p' <- atomically (readTVar p)
  mapM killThread (t:p')

repeatAccept s p = do
  a <- accept s
  t <- forkFinally (echoHandler a) (exitPool p) -- Error here, forkIO instead compiles fine.. (and I guess actually should work just fine too?)
  atomically $ do
    p' <- readTVar p
    writeTVar p (t:p')
  repeatAccept s p

exitPool :: Pool -> a -> IO ()
exitPool pool = \_ -> do
  tid <- myThreadId
  atomically $ do
    pool' <- readTVar pool
    writeTVar pool $ filter (/=tid) pool'
    return ()

echoHandler :: ConnectionHandler
echoHandler a@(hdl,_,_) = repeatUntilExit hdl hdl echoToHandleAndStdout ""
  where echoToHandleAndStdout x = hPutChar hdl x >> putChar x

repeatUntilExit :: Handle -> Handle -> (Char -> IO ()) -> [Char] -> IO ()
repeatUntilExit hIn hOut f "exit\n" = hPutStrLn hOut "bye\n"
repeatUntilExit hIn hOut f x = hGetChar hIn >>= \c -> f c >> repeatUntilExit hIn hOut f (appendToLastFive c)
  where appendToLastFive a = (reverse . (:)a . take 4 . reverse) x

forkFinally :: Exception e => IO a -> (Either e a -> IO ()) -> IO ThreadId
forkFinally action and_then =
  mask $ \restore ->
    forkIO $ try (restore action) >>= and_then
4

1 回答 1

6

forkFinally在最新的 Control.Concurrent 中键入签名:

forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId

forkFinally在您的代码中键入签名:

forkFinally :: Exception e => IO a -> (Either e a -> IO ()) -> IO ThreadId

您试图概括异常类型。如果异常类型可以从forkFinally的第二个参数推导出来,这不是问题。但这是forkFinally的第二个参数:

exitPool p :: a' -> IO ()

类型检查器试图统一Either e a -> IO ()a' -> IO ()最终无法推断出是什么e

一般解决方案:指定显式类型。例如

t <- forkFinally (echoHandler a) (exitPool p :: Either SomeException () -> IO ())

更好的具体解决方案:将原始类型签名恢复为forkFinally. 只捕获一组有限的异常似乎没有意义。

于 2013-03-14T21:42:23.377 回答