4

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

4

1 回答 1

7

ScopedTypeVariables扩展将语义值添加到顶级forall量词。它为绑定主体上的类型变量提供范围。

没有它forall,第a3 行的类型变量与第 1 行的类型变量是不同的类型变量a。错误消息通过标记它们a0和来表明这一点a1。如果没有相同的类型,第 3 行的类型是模棱两可的,因为它完全不受约束。

于 2013-01-01T23:26:30.803 回答