Reputation: 1864
I am trying to understand this Elm construct:
type Item = Item { name : String, data : String }
type alias Item = {...}
, it does not provide a "constructor".> 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`.
Upvotes: 4
Views: 94
Reputation: 36375
It is a Union Type with a single constructor which happens to take a Record as its only type parameter.
The fact that the type name and constructor name are both Item
is a common idiom, but holds no significance. It could easily be any other valid constructor name:
type Item = Foo { name : String, data : String }
For practical purposes, it can be useful to use a type alias for the internal record type so you can more succinctly pull values out. If you move things around a little bit:
type alias ItemContents = { name : String, data : String }
type Item = Item ItemContents
You could provide a function that returns the internal contents:
getItemContents : Item -> ItemContents
getItemContents (Item contents) = contents
And now it could be used like this REPL example:
> 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
Upvotes: 6