存在量化构造函数列表

List of Existentially Quantified Constructors

我有以下数据类型:

{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ExtendedDefaultRules #-}

class ToString a where

data M = forall a. (ToString a) => B a

在 GHCI 中,我可以毫无问题地执行以下操作:

let bs = [B, B]

但是如果我尝试在编译文件中执行此操作,则会出现以下错误:

No instance for (ToString a0) arising from a use of ‘B’
The type variable ‘a0’ is ambiguous
Relevant bindings include
  bs :: [a0 -> M] (bound at src/My/Module:7:1)

我缺少哪个扩展允许我创建 B 的列表,如图所示?或者我错过了 GHCI 添加的什么?

这是因为 GHCi 没有开启单态限制,而 GHC(默认情况下)开启了。为了证明,以下文件类型检查:

{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE NoMonomorphismRestriction #-}

class ToString a where

data M = forall a. (ToString a) => B a

bs = [B, B]

bs的推断类型是相当无用的,当然:

*Main> :t bs
bs :: ToString a => [a -> M]

如果你不想关闭单态限制,你可以在 bs 的定义中添加类型签名:

{-# LANGUAGE ExistentialQuantification #-}

class ToString a where

data M = forall a. (ToString a) => B a

bs :: (ToString a) => [a -> M]
bs = [B, B]