polyTypeOf 很神秘

发布于 2024-12-12 21:55:47 字数 824 浏览 1 评论 0原文

PolyTypeable 是 Typeable 的模拟多态类型。但它的工作原理相当不可预测:

ghci> :t show
show :: Show a => a -> String
ghci> polyTypeOf show
a1 -> [Char]
ghci> :t fromEnum 
fromEnum :: Enum a => a -> Int
ghci> polyTypeOf fromEnum 

<interactive>:1:12:
    Ambiguous type variable `a0' in the constraint:
      (Enum a0) arising from a use of `fromEnum'
    Probable fix: add a type signature that fixes these type variable(s)
    In the first argument of `polyTypeOf', namely `fromEnum'
    In the expression: polyTypeOf fromEnum
    In an equation for `it': it = polyTypeOf fromEnum

库源代码很难理解,您能解释一下为什么 polyTypeOf 接受某些参数集而无法接受其他参数,甚至非常相似?

PolyTypeable is an analog of Typeable for polymorphic types. But it works rather unpredictably:

ghci> :t show
show :: Show a => a -> String
ghci> polyTypeOf show
a1 -> [Char]
ghci> :t fromEnum 
fromEnum :: Enum a => a -> Int
ghci> polyTypeOf fromEnum 

<interactive>:1:12:
    Ambiguous type variable `a0' in the constraint:
      (Enum a0) arising from a use of `fromEnum'
    Probable fix: add a type signature that fixes these type variable(s)
    In the first argument of `polyTypeOf', namely `fromEnum'
    In the expression: polyTypeOf fromEnum
    In an equation for `it': it = polyTypeOf fromEnum

The library source code is quite hard to understand, could you explain why does polyTypeOf accept certain set of arguments and fails to accept other, even very similar?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

哭泣的笑容 2024-12-19 21:55:47

原因与此相同

Prelude> show undefined
"*** Exception: Prelude.undefined
Prelude> fromEnum undefined

<interactive>:0:1:
    Ambiguous type variable `a0' in the constraint:
      (Enum a0) arising from a use of `fromEnum'
    Probable fix: add a type signature that fixes these type variable(s)
    In the expression: fromEnum undefined
    In an equation for `it': it = fromEnum undefined

,即 ghci 的扩展默认规则允许它解决 Show 约束的歧义性,但不能解决 Enum 约束的歧义性。如果您尝试使用 foo = polyTypeOf show 编译源文件,您还会收到不明确的类型变量错误(除非您使用 {-# LANGUAGE ExtendedDefaultRules #-})。

The reason is the same as for

Prelude> show undefined
"*** Exception: Prelude.undefined
Prelude> fromEnum undefined

<interactive>:0:1:
    Ambiguous type variable `a0' in the constraint:
      (Enum a0) arising from a use of `fromEnum'
    Probable fix: add a type signature that fixes these type variable(s)
    In the expression: fromEnum undefined
    In an equation for `it': it = fromEnum undefined

namely, ghci's extended defaulting rules allow it to resolve the ambiguity for a Show constraint, but not for an Enum constraint. If you try to compile a source file with foo = polyTypeOf show, you also get an ambiguous type variable error (unless you use {-# LANGUAGE ExtendedDefaultRules #-}).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文