首页 > 解决方案 > Haskell 可以显示多态类型的对象吗?

问题描述

在 Doets 的The Haskell Road to Logic, Math, and Programming一书中,第 152 页给出了

在此处输入图像描述

但是,当我输入[]ghc 时,我得到[]

$> :t []
[] :: [a]

所以 Haskell 确实显示了多态数据类型,所以我在这里遗漏了什么,还是这本书?

也许这是后来添加到 Haskell 中的东西;这本书写于 2004 年。

标签: haskelltypespolymorphism

解决方案


这是默认(如果只需要用于单一类型,则将类多态表达式转换为单态表达式的过程)加上ghci 的扩展默认规则的结果。你的书可能有一个关于默认的部分,当然 ghci 的额外默认规则不会在那里描述。使用扩展默认,多Show a => [a]态类型[()]在打印前默认为单态类型。您可以通过禁用扩展默认值来重现本书的错误(好吧,无论如何,类似的错误):

> :set -XNoExtendedDefaultRules
> []
<interactive>:2:1: error:
    • Ambiguous type variable ‘a0’ arising from a use of ‘print’
      prevents the constraint ‘(Show a0)’ from being solved.
      Probable fix: use a type annotation to specify what ‘a0’ should be.
      These potential instances exist:
        instance Show Ordering -- Defined in ‘GHC.Show’
        instance Show Integer -- Defined in ‘GHC.Show’
        instance Show a => Show (Maybe a) -- Defined in ‘GHC.Show’
        ...plus 22 others
        ...plus 11 instances involving out-of-scope types
        (use -fprint-potential-instances to see them all)
    • In a stmt of an interactive GHCi command: print it

推荐阅读