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



这是代码:

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

据我了解,我必须以某种方式告诉编译器,solveProblemreadProblem使用的Problem实例是同一类型,但我认为没有办法声明这一点。为什么它不能自己弄清楚呢?

你不需要告诉编译器它必须是相同的类型,编译器自己计算出来。但是,它无法确定要使用哪种类型。该问题的规范著名示例是

foo = show . read

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

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

现在,编译器如何确定?

您的readAndSolve将具有以下类型

readAndSolve :: Problem p => String -> String

最新更新