这个榆树构造的名称是什么:type X = X {...}?

What is the name of this elm construct: type X = X {...}?

我试图理解这个 Elm 结构:

type Item = Item { name : String, data : String }
> 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`.

它是一个 Union Type with a single constructor which happens to take a Record 作为它唯一的类型参数。

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

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

出于实际目的,为内部记录类型使用类型别名可能很有用,这样您可以更简洁地提取值。如果你稍微移动一下:

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

type Item = Item ItemContents

您可以提供 returns 内部内容的函数:

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