这个榆树构造的名称是什么:type X = X {...}?
What is the name of this elm construct: type X = X {...}?
我试图理解这个 Elm 结构:
type Item = Item { name : String, data : String }
- 它类似于记录,但行为却大不相同。
- 它对于定义递归数据模型很有用。
- 与
type alias Item = {...}
不同,它不提供 "constructor"。
- 我在 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`.
- 这个结构怎么称呼?
- 如何访问包含的字段?
它是一个 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
我试图理解这个 Elm 结构:
type Item = Item { name : String, data : String }
- 它类似于记录,但行为却大不相同。
- 它对于定义递归数据模型很有用。
- 与
type alias Item = {...}
不同,它不提供 "constructor"。 - 我在 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`.
- 这个结构怎么称呼?
- 如何访问包含的字段?
它是一个 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