为什么编译器不解析函数内的隐式约束类型变量?

时间:2012-04-28 16:43:29

标签: haskell

以下是代码:

class Problem p where
    readProblem :: String -> p
    solveProblem :: p -> String

readAndSolve = solveProblem . readProblem

这是GHC产生的错误信息:

Ambiguous type variable `b0' in the constraint:
  (Problem b0) arising from a use of `readProblem'
Probable fix: add a type signature that fixes these type variable(s)
In the second argument of `(.)', namely `readProblem'
In the expression: solveProblem . readProblem
In an equation for `readAndSolve':
    readAndSolve = solveProblem . readProblem

据我所知,我必须以某种方式告诉编译器ProblemsolveProblem使用的readProblem实例是同一类型,但我认为没有办法声明它。为什么它不能自己解决这个问题呢?

1 个答案:

答案 0 :(得分:8)

您无需告诉编译器它必须是同一类型,编译器会自行解决。但是,它无法弄清楚使用哪种类型。这个问题的典型着名例子是

foo = show . read

如果foo有合法类型,那就是

foo :: (Read a, Show a) => String -> String

现在,编译器如何确定?

您的readAndSolve将具有

类型
readAndSolve :: Problem p => String -> String