0
は(http://lpaste.net/180651から)次のコードを検討:なぜGHCはこのタイプを推論できないのですか?
test.hs:11:33: error:
• Could not deduce (Natural n0) arising from a use of ‘dim’
from the context: Natural n
bound by the type signature for:
bad_fromList :: Natural n => [a] -> V n a
at test.hs:10:1-41
The type variable ‘n0’ is ambiguous
• In the second argument of ‘(==)’, namely ‘dim v’
In the expression: length l == dim v
In the expression: if length l == dim v then v else undefined
なぜGHCiのタイプを推測することができない。
{-# LANGUAGE ScopedTypeVariables #-}
class Natural n
newtype V n a = V [a]
dim :: Natural n => V n a -> Int
dim = undefined -- defined in my actual code
bad_fromList :: Natural n => [a] -> V n a
bad_fromList l = if length l == dim v then v else undefined -- this is line 11
where v = V l
good_fromList :: forall n a. Natural n => [a] -> V n a
good_fromList l = if length l == dim v then v else undefined
where v = V l :: V n a
GHCiの次のエラーメッセージを表示しますか?
または、次のコードでは、pure 'とgood_fがコンパイルされますが、bad_fでは同様のエラーメッセージが表示されます。どうして?
pure' :: Natural n => a -> V n a
pure' x = v
where v = V $ replicate (dim v) x
bad_f :: Natural n => [a] -> (V n a, Int)
bad_f xs = (v, dim v)
where v = V xs
good_f :: Natural n => a -> (V n a, Int)
good_f x = (v, dim v)
where v = V $ replicate (dim v) x
問題は、 'v'は**すべての可能な型' n'に対して 'V n a'型を持っていることです。ハスケルがオープンな世界の仮定に頼っているので、 'Natural n'のどのインスタンスがそこで使われるべきか、そして' n0'があいまいであるというエラーを知る方法はありません:GHCはランダムなタイプを選びたくありません「薄暗い」と呼ぶことができる。コードをあいまいにしないでください。 – Bakuriu
ここでの型は実際にはあいまいではありませんが、これらのエラーは、コンパイラが必要以上に一般的な型シグニチャを推測しようとしているためです。 '-XMonoLocalBinds'を有効にすると、あなたのコードは動作します(https://ideone.com/GsEHSO)。 – user2407038
@ user2407038ありがとう! MonoLocalBindsを使うことには欠点がありますか? – Kevin