Consider a typical type definition of a Msg type in elm:

type Msg

= UserInput String

| LoggedIn User

| Guest User

| ClickedLogoff

In this definition, the types are

Msg : this is the type that is being defined.

: this is the type that is being defined. String : this is the (built-in) type we are using ‘inside’ the Msg type.

: this is the (built-in) type we are using ‘inside’ the type. User : some custom type

What about UserInput , LoggedIn , Guest and ClickedLogoff ?

They are functions called constructors. You get them for free. If you define the type, you get the constructors as well.

Constructor functions

UserInput is a function with a capitalized name. It has the signature String -> Msg . Which means it takes a String and outputs a Msg .

And it’s called a constructor. Because it constructs a Msg type. In

something = UserInput value , the UserInput value part constructs a Msg . So the variable something will be of the type Msg and will hold the resulting value of UserInput value .

LoggedIn is also a function, which takes a User as its argument. It outputs a Msg too. And Guest is a function too, with the exact same argument User , and the same signature.

ClickedLogoff is also a constructor, of an equally useful nature (albeit somewhat boring). It takes no arguments, and simply returns a Msg .

You typically call a function like UserInput in your view. You pass it to the onInput handler, when you render the input field:

input [ type_ "text", onInput UserInput ] ...

The onInput handler is from the Html.Events library. It has the following type signature.

This function takes one argument, a function. It wants you to provide a function that turns a String into a msg . The msg in the signature is in lowercase. The onInput function does not care what type the msg is. That is up to you. It will simply include that type in the output of the function, in the Attribute msg . ( Attribute msg is the type for attributes of HTML elements. In the Html.Attribute package there is some explanation and examples)

The UserInput constructor defined earlier matches this signature and does exactly what’s needed here: it takes a String (which is whatever the user typed in the input field), and turns it into a Msg .

Constructors in pattern matching

You can also use these constructors to access the contents of a variable later on. Using a case .. of statement we can

Find out which constructor was used. Access the contents “behind” that constructor (if there is any).

In the example, both the LoggedIn constructor and the Guest constructor carry a User . With a case statement, we can find out which constructor was used, and access the user information: