1

コードは次のとおりです。

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

私が理解しているように、andProblemによって使用されるインスタンスが同じ型であることを何らかの形でコンパイラに伝える必要がありますが、それを宣言する方法がわかりません。そして、なぜそれを自分で理解できないのですか?solveProblemreadProblem

4

1 に答える 1

8

同じ型でなければならないことをコンパイラーに伝える必要はありません。コンパイラーはそれを自分で判断します。ただし、どのタイプを使用するかはわかりません。問題の標準的な有名な例は

foo = show . read

foo正当なタイプがある場合、それは

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

では、コンパイラはどのようにして a を決定できるのでしょうか?

あなたreadAndSolveはタイプを持っているでしょう

readAndSolve :: Problem p => String -> String
于 2012-04-28T16:49:17.087 に答える