我有以下数据类型:
{-# 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正在添加什么?
答案 0 :(得分:4)
这是因为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]