[英]Why can't GHC deduce type equality on a class type family in a Rank 2 type?
[英]Why can't GHC deduce this type?
考虑以下代码段(来自http://lpaste.net/180651 ):
{-# 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给出以下错误消息:
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为什么无法推断类型?
或者,在下面的代码中,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
如user2407038所建议,启用-XMonoLocalBinds可使代码正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.