这个 elm 结构的名称是什么:type X = X {...}?

4
我正在尝试理解这个Elm结构:
type Item = Item { name : String, data : String }
  • 它看起来像是一条记录,但它的行为非常不同。
  • 它有助于定义递归数据模型。
  • type alias Item = {...}不同,它不提供“构造函数”。
  • 我在Elm语法指南中找不到它。
  • 我无法弄清如何访问它的字段:
> item = Item { name = "abc", data  = "def" } 
Item { name = "abc", data = "def" } : Repl.Item

> item.name
-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

`item` does not have a field named `name`.

6|   item.name
     ^^^^^^^^^ The type of `item` is:

    Item

Which does not contain a field named `name`.
  • 这个结构叫什么?
  • 如何访问其中包含的字段?
1个回答

6

这是一个联合类型,只有一个构造函数,它恰好以记录作为唯一的类型参数。

类型名称和构造函数名称都是Item是一种常见的习惯用法,但没有实际意义。它可以很容易地是任何其他有效的构造函数名称:

type Item = Foo { name : String, data : String }

为了实际应用,使用类型别名来定义内部记录类型可以更简洁地提取值。如果稍微调整一下:

type alias ItemContents = { name : String, data : String }

type Item = Item ItemContents

您可以提供一个返回内部内容的函数:
getItemContents : Item -> ItemContents
getItemContents (Item contents) = contents

现在它可以像这样在 REPL 示例中使用:

> item = Item { name = "abc", data  = "def" }
Item { name = "abc", data = "def" } : Repl.Item
> contents = getItemContents item
{ name = "abc", data = "def" } : Repl.ItemContents
> contents.name
"abc" : String

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接