1

I'm just starting out with Elm, so be nice:)

In the "Random" example of the official Elm Guide the model seems to be initialized with the value 1 like this:

type alias Model =
  { dieFace : Int
  }


init : (Model, Cmd Msg)
init =
(Model 1, Cmd.none)

My understanding of this is that the code

Model 1

sets the value of the dieFace attribute in the record. Is this correct and if so: what is this strange syntax for setting the attribute of a record? I would have expected something along the lines of

{ model | dieFace = 1 }
swelet
  • 8,192
  • 5
  • 33
  • 45

1 Answers1

5

Model is a type alias for a record which has a single int value called dieFace.

There are a few ways to create a value of that type:

Model 1 -- treats Model as a function with a single parameter

{ dieFace = 1 } -- creates a record that happens to coincide with the Model alias

The strange syntax you see in { model | dieFace = 1 } is short-hand for creating a new value based off an existing record value but changing one or more fields. It perhaps doesn't make much sense when your record type has a single field so let's create an arbitrary example:

type alias ColoredDie = { dieFace: Int, color: String }

You can play around in the Elm REPL and perhaps this will help it make sense:

> blue3 = ColoredDie 3 "blue"
{ dieFace = 3, color = "blue" } : Repl.ColoredDie
> red3 = { blue3 | color = "red" }
{ dieFace = 3, color = "red" } : { dieFace : Int, color : String }
> red4 = { red3 | dieFace = 4 }
{ dieFace = 4, color = "red" } : { color : String, dieFace : number }
> green6 = { red4 | color = "green", dieFace = 6 }
{ dieFace = 6, color = "green" } : { color : String, dieFace : number }

You can read up on Elm's record syntax here.

Chad Gilbert
  • 36,115
  • 4
  • 89
  • 97