gpt4 book ai didi

haskell - 省略显式 forall 会产生模棱两可的类型错误

转载 作者:行者123 更新时间:2023-12-04 23:58:09 24 4
gpt4 key购买 nike

我遇到了一个函数无法进行类型检查的情况,除非我在其类型签名的开头显式添加一个 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”相当于在所有相关类型变量的开头隐式附加 forall(如 GHC 文档中所建议: http://www.haskell.org/ghc/docs/7.4.2/html/users_guide/other-type-extensions.html)。为什么第一个代码片段不进行类型检查,而第二个代码片段呢?

最佳答案

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

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

关于haskell - 省略显式 forall 会产生模棱两可的类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14115191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com