我正在尝试将程序的错误处理转换为使用异常。我构建了一个 REPL 来控制我的模拟,同时我还处理错误:
> repl :: Sim -> IO Sim
> repl old_sim = do
> new_sim <- E.catch (do line <- getLine
> commands <- parseCommand line
> runCommands commands old_sim)
> (\err -> do putStrLn . show $ err
> return old_sim)
> if alive new_sim
> then repl new_sim
> else return new_sim
parseCommands 或 runCommands 都可能失败 String
,两者都会返回 IO Sim
。
当我加载文件时,我收到这个巨大的错误:
Prelude> :l simple_sim
[1 of 1] Compiling Main ( simple_sim.lhs, interpreted )
simple_sim.lhs:95:18:
Ambiguous type variable `a0' in the constraints:
(E.Exception a0) arising from a use of `E.catch'
at simple_sim.lhs:95:18-24
(Show a0) arising from a use of `show' at simple_sim.lhs:100:49-52
Probable fix: add a type signature that fixes these type variable(s)
In a stmt of a 'do' expression:
new_sim <- E.catch
(do { line <- getLine;
commands <- parseCommand line;
runCommands commands old_sim })
(\ err
-> do { putStrLn . show $ err;
return old_sim })
In the expression:
do { new_sim <- E.catch
(do { line <- getLine;
commands <- parseCommand line;
runCommands commands old_sim })
(\ err
-> do { putStrLn . show $ err;
.... });
if alive new_sim then repl new_sim else return new_sim }
In an equation for `repl':
repl old_sim
= do { new_sim <- E.catch
(do { line <- getLine;
commands <- parseCommand line;
.... })
(\ err -> do { ... });
if alive new_sim then repl new_sim else return new_sim }
Failed, modules loaded: none.
具体:
Probable fix: add a type signature that fixes these type variable(s)
我应该在哪里插入这个类型签名?
最佳答案
您需要在 err 上使用它来确定您要 try catch 哪些异常。
关于exception - Haskell 错误 : "Ambiguous type variable" in Exception. 捕获;需要类型签名,但是在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5524201/