我有以下数据类型:
{-# 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)
我错过了哪个扩展名(s),这将允许我创建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]