Reading Note: Model and Record Data Type in Elm

2022-03-27softwarefunctionalelm

Model

Record Data Type

> dog = { name = "Tucker", age = 11 }
{ age = 11, name = "Tucker" } : { age : number, name: String }

Let write a function for the dog to have a birthday:

> haveBirthday d = { name = d.name , age = d.age + 1 }
<function>
    : { b | age : number, name : a } -> { age : number, name : a }

The haveBirthday function takes a record of type b that must have an age field of type number and a name field of type a.

This is an extensive record.

Another example of extensive record:

type alias Contact c =
  { c
      | name : String
      , email : String
      , phone : String
  }

It means that any record with name, email and phone String fields is a Contact.

Get back to the haveBirthday function, you can use it on the original dog to create a new instance of a dog record.

> olderDog = haveBirthday dog
{ age = 12, name = "Tucker" } : { age : number, name : String }

> dog
{ age = 11, name = "Tucker" } : { age : number, name: String }

So, when using Elm, you do not mutate the model values. You create a new value from the original one.

References