了解 Haskell 的 Data.Data 包的构造类型

Understanding Constr type of Data.Data package of Haskell

我想了解 Data.Data 包的 Constr 类型。考虑下面的会话。 dataTypeConstrs returns Constr 的列表,Maybe 的零参数和单参数构造函数。由于明显的类型错误,尝试重新创建列表失败。它是 GHC 对 Constr 值的特殊行为吗?

$ ghci
GHCi, version 7.10.2: http://www.haskell.org/ghc/  :? for help
Prelude> :set -XScopedTypeVariables
Prelude> :module +Data.Data
Prelude Data.Data> dataTypeConstrs (dataTypeOf (Nothing :: Maybe ()))
[Nothing,Just]
Prelude Data.Data> :i it
it :: [Constr]  -- Defined at <interactive>:4:1

Prelude Data.Data> let i2 :: [Constr] = [Nothing,Just]

<interactive>:6:23:
    Couldn't match expected type ‘Constr’ with actual type ‘Maybe a0’
    In the expression: Nothing
    In the expression: [Nothing, Just]

这不是实际构造函数的列表,而是构造函数表示的列表。它的 Show 实例使用快速而松散的输出,这使它看起来与众不同。

假装它是

[ Constr{ name = "Nothing", args = 0, ... }
, Constr{ name = "Just", args = 1, ... }
]

除了以松散的方式显示。

更准确地说,那是内部,不透明的构造函数表示。使用 constr* 观察器检查 Constr.

类型的值