[英]Omitting explicit forall yields ambiguous type error
我遇到了函数无法进行类型检查的情况,除非我明确地在其类型签名的开头添加了forall。
有问题的功能是:
test :: (Typeable a) => a -> a
test x
| typeOf (undefined :: a) == typeOf (undefined :: a) = x
| otherwise = x
GHC对以上内容发出以下警告:
Ambiguous type variable `a0' in the constraint:
(Typeable a0) arising from a use of `typeOf'
Probable fix: add a type signature that fixes these type variable(s)
In the first argument of `(==)', namely `typeOf (undefined :: a)'
In the expression:
typeOf (undefined :: a) == typeOf (undefined :: a)
In a stmt of a pattern guard for
an equation for `test':
typeOf (undefined :: a) == typeOf (undefined :: a)
Ambiguous type variable `a1' in the constraint:
(Typeable a1) arising from a use of `typeOf'
Probable fix: add a type signature that fixes these type variable(s)
In the second argument of `(==)', namely `typeOf (undefined :: a)'
In the expression:
typeOf (undefined :: a) == typeOf (undefined :: a)
In a stmt of a pattern guard for
an equation for `test':
typeOf (undefined :: a) == typeOf (undefined :: a)
所以它没有统一两种类型的未定义值。 但是,如果我在前面添加一个forall:
test :: forall a. (Typeable a) => a -> a
test x
| typeOf (undefined :: a) == typeOf (undefined :: a) = x
| otherwise = x
它汇编得很好。 这是在GHC 7.4.2中使用的
{-# LANGUAGE GADTs, StandaloneDeriving, DeriveDataTypeable,
ScopedTypeVariables, FlexibleInstances, UndecidableInstances,
Rank2Types #-}
我的印象是,在类型签名中省略“forall”相当于在所有相关类型变量上隐含地附加了foralls(如GHC文档中所述: http : //www.haskell.org/ghc/docs/ 7.4.2 / html / users_guide / other-type-extensions.html )。 为什么第一个代码片段不进行类型检查,而第二个代码片段呢?
ScopedTypeVariables
扩展将语义值添加到顶级forall
量词。 它是在绑定体上提供类型变量的范围。
没有那个forall
,第3行的类型变量a
是与第a
行的类型变量不同的类型变量。错误消息通过将它们标记为a0
和a1
指示这一点。 如果没有相同的类型,第3行的类型是模糊的,因为它完全不受约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.