【问题标题】:Haskell Error: "Ambiguous type variable" in Exception.catch; Need type signature, but where?Haskell 错误:Exception.catch 中的“不明确的类型变量”;需要类型签名,但在哪里?
【发布时间】:2011-04-02 15:57:17
【问题描述】:

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

我应该在哪里插入这个类型签名?

【问题讨论】:

标签: exception haskell types


【解决方案1】:

您需要在 err 上确定您要捕获的异常。

【讨论】:

  • 但是如果我将它添加为 (\err ::E.SomeException -> ...),我会得到“非法结果类型签名 `E.SomeException',模式中不再支持结果签名匹配”
  • 您需要打开一些扩展才能将类型签名放入 lambda。但是你可以把它放在错误的任何地方。或者在函数本身上。
  • anm 添加&gt; {-# LANGUAGE ScopedTypeVariables #-}的第一行。
  • @Anm 啊是的,正如我们刚才在 IRC 上所说,使用 (\(err :: E.SomeException) -&gt; ...)
猜你喜欢
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-19
  • 1970-01-01
相关资源
最近更新 更多