简体   繁体   English

现有量化构造函数列表

[英]List of Existentially Quantified Constructors

I have the following data type: 我有以下数据类型:

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

class ToString a where

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

In GHCI I can do the following with no problems: 在GHCI中,我可以毫无问题地执行以下操作:

let bs = [B, B]

But if I try to do this in a compiled file, I get the following error: 但是,如果我尝试在编译文件中执行此操作,则会收到以下错误:

 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) 

Which extension(s) am I missing that would allow me to create the list of B as shown? 我缺少哪些扩展名,这些扩展名允许我创建所示的B列表? Or what am I missing that GHCI is adding? 还是我不知道GHCI正在添加什么?

This is because GHCi doesn't turn on the monomorphism restriction, and GHC (by default) does. 这是因为GHCi不会打开单态限制,而GHC(默认情况下)会打开。 To witness, the following file typechecks: 为了证明这一点,需要检查以下文件:

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

class ToString a where

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

bs = [B, B]

The inferred type of bs is fairly useless, of course: 当然, bs的推断类型是毫无用处的:

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

If you don't want to turn off the monomorphism restriction, you can just add a type signature to the definition of bs : 如果您不想关闭单态性限制,可以在bs的定义中添加类型签名:

{-# LANGUAGE ExistentialQuantification #-}

class ToString a where

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM