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

bog*_*ogl 4 syntax elm

我试图理解这个榆树构造:

type Item = Item { name : String, data : String }
Run Code Online (Sandbox Code Playgroud)
  • 它类似于记录,但它的行为却截然不同.
  • 它对于定义递归数据模型很有用.
  • type alias Item = {...}与之不同,它不提供"构造函数".
  • 我在Elm Syntax指南中找不到它.
  • 我无法弄清楚如何访问其字段:
> 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`.
Run Code Online (Sandbox Code Playgroud)
  • 这个结构如何调用?
  • 你如何访问包含的字段?

Cha*_*ert 6

它是具有单个构造函数的Union Type,它恰好将Record作为其唯一的类型参数.

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

type Item = Foo { name : String, data : String }
Run Code Online (Sandbox Code Playgroud)

出于实际目的,对内部记录类型使用类型别名会很有用,这样您就可以更简洁地提取值.如果你移动一点点:

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

type Item = Item ItemContents
Run Code Online (Sandbox Code Playgroud)

您可以提供一个返回内部内容的函数:

getItemContents : Item -> ItemContents
getItemContents (Item contents) = contents
Run Code Online (Sandbox Code Playgroud)

现在它可以像这个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
Run Code Online (Sandbox Code Playgroud)