exception - Haskell 错误 : "Ambiguous type variable" in Exception. 捕获;需要类型签名,但是在哪里?

标签 exception haskell types

我正在尝试将程序的错误处理转换为使用异常。我构建了一个 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/

相关文章:

java - Java中try catch block 中可捕获异常的规则是什么?

haskell - Haskell 的 Erlang 等价物 where/partial/lambda

树的 Haskell map

oop - 在 Haskell 中创建绑定(bind)到记录的方法

c++ - 如果我使用 "throw;"无异常抛出会发生什么?

java - 设置迭代器的并发修改异常

java - 向抛出的异常添加自定义消息,同时在 Java 中维护堆栈跟踪

haskell - Haskell 中的运行长度编码

c - 包含 2 位十六进制值的数组应使用哪种 C 数据类型?

c# - 如何检查一个值是否可以转换为泛型类型?