我试图理解这个榆树构造:
type Item = Item { name : String, data : String }
Run Code Online (Sandbox Code Playgroud)
type alias Item = {...}与之不同,它不提供"构造函数".> 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)
它是具有单个构造函数的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)
| 归档时间: |
|
| 查看次数: |
71 次 |
| 最近记录: |