以下是代码:
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
据我所知,我必须以某种方式告诉编译器Problem
和solveProblem
使用的readProblem
实例是同一类型,但我认为没有办法声明它。为什么它不能自己解决这个问题呢?
答案 0 :(得分:8)
您无需告诉编译器它必须是同一类型,编译器会自行解决。但是,它无法弄清楚使用哪种类型。这个问题的典型着名例子是
foo = show . read
如果foo
有合法类型,那就是
foo :: (Read a, Show a) => String -> String
现在,编译器如何确定?
您的readAndSolve
将具有
readAndSolve :: Problem p => String -> String