我遇到了一个函数无法进行类型检查的情况,除非我在其类型签名的开头显式添加一个 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 a :
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)。为什么第一个代码片段不进行类型检查,而第二个代码片段呢?