bogl
bogl

Reputation: 1864

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

I am trying to understand this Elm construct:

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`.

Upvotes: 4

Views: 94

Answers (1)

Chad Gilbert
Chad Gilbert

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

Related Questions