Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm: How does this init work?

Tags:

elm

type alias Model =
  { dieFace : Int
  }


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

Why does the integer 1 get passed to the model ala Model 1?

The type alias seems to requiring a record?

like image 229
Rich Avatar asked Dec 17 '25 21:12

Rich


1 Answers

There is not so much un-explained magic in Elm (for good reason), but one bit is the type and type alias constructors. Whenever you create a type (alias) you get a constructor function for free. So, to use your example,

type alias Model =
  { dieFace : Int
  }

gives you a (somewhat weird-looking) constructor function

Model : Int -> Model 

for free. If you add more entries to your record, like this

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

the constructor function takes more arguments.

Model : Int -> String -> Model 

The order of these are the same order as the record entries, so if you change the order of your type aliases, you'll have to change the argument order to to the constructor function.

Union types work in a similar way.

type Shape
  = Circle Int
  | Square Int Int 

quietly creates constructors:

Circle: Int -> Shape 
Square : Int -> Int -> Shape
like image 147
Simon H Avatar answered Dec 21 '25 20:12

Simon H



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!