Elm: How does this init work?

type alias Model =
  { dieFace : Int
  }


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

      

Why is an integer being 1

passed to the ala model Model 1

?

Seems like the type alias needs to be written?

+3


source to share


2 answers


There isn't a lot of explainable magic in Elm (for good reason), but one bit is the type and type alias constructors. Whenever you create a type (alias), you get the constructor function for free. So, to use your example,

type alias Model =
  { dieFace : Int
  }

      

gives you a (somewhat strange) constructor function

Model : Int -> Model 

      

is free. If you add more entries to your post, for example

type alias Model =
  { dieFace : Int
  , somethingElse : String
  }

      

the constructor function takes more arguments.



Model : Int -> String -> Model 

      

The order of these actions is the same order as the entries, so if you change the order of your type's aliases, you have to change the order of the arguments to the constructor function.

Union types work in a similar way.

type Shape
  = Circle Int
  | Square Int Int 

      

silently creates constructors:

Circle: Int -> Shape 
Square : Int -> Int -> Shape

      

+7


source


Model 1

Used in "Model" as a positional notation constructor. It is equal{dieFace = 1}


Here's another example:

type alias Rcd =
    { first : String
    , second : Int 
    }

      



Rcd can be built in two ways:

Rcd "some string" 4
{ first = "some string" , second = 4}

      

The first option is just shorthand and is often used to initialize records.

+3


source







All Articles