【问题标题】:What is '[] and ': in Haskell?'[] 和 ': 在 Haskell 中是什么?
【发布时间】:2019-05-29 22:15:16
【问题描述】:

我在一些地方看到过这种'[]': 语法,尤其是在HListHVect 等异构列表包中。

例如,异构向量HVect定义为

data HVect (ts :: [*]) where
    HNil :: HVect '[]
    (:&:) :: !t -> !(HVect ts) -> HVect (t ': ts)

在 GHCi 中,扩展名为 TemplateHaskellDataKinds,我明白了

> :t '[]
'[] :: template-haskell-2.13.0.0:Language.Haskell.TH.Syntax.Name
> :t '(:)
'(:) :: template-haskell-2.13.0.0:Language.Haskell.TH.Syntax.Name

我的印象是这与依赖类型和种类等有关,与模板 haskell 无关。

搜索引擎和hooglehayoo 处理带有'[]': 的查询相当糟糕,因此问题是:这些'[]': 的名称是什么东西? 非常欢迎提供文档或教程。

【问题讨论】:

标签: haskell types type-level-computation data-kinds heterogeneous-array


【解决方案1】:

DataKinds 允许在类型级别使用术语级别的构造函数。

之后

data T = A | B | C

可以编写由值T 索引的类型

data U (t :: T) = ...
foo :: U A -> U B -> ...

然而,AB 在这里被用作类型,而不是值。因此,必须使用引用来“提升”它们:

data U (t :: T) = ...
foo :: U 'A -> U 'B -> ...

熟悉的列表语法也是如此。 '[] 是一个空列表,在类型级别提升。 '[a,b,c]a ': b ': c ': '[] 相同,是在类型级别提升的列表。

type           :: kind
'[]            :: [k]   -- polykinded! works for any kind k
'[ 'A, 'B, 'C] :: [T]   -- mind the spaces, we do not want the char '['
'A ': '[]      :: [T]
'[ Int, Bool ] :: [*]   -- a list of types
'[ Int ]       :: [*]   -- a list of types with only one element
[Int]          :: *     -- a type "list of Int"

注意最后两种情况,其中引号消除了语法的歧义。

【讨论】:

  • 也可以写' ['A, 'B, 'C] 来消除您的示例的歧义。
【解决方案2】:

Thinking with Types 作者:Sandy Maguire (http://thinkingwithtypes.com)

一般来说,这可能是有关 Haskell 中类型级编程主题的一个很好的资源。 “解除限制”一章涉及DataKinds 和提升的构造函数。

(免责声明:无从属关系。)

【讨论】:

    猜你喜欢
    • 2013-10-31
    • 2015-09-14
    • 2016-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多