Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding types in Elm

Trying to learn Elm with a background in JS and little experience in strongly- and statically-typed languages, I find that the major difficulty revolves around the type syntax (and what types are useful for in Elm generally). Unfortunately, I don't find the docs very helpful in this respect.

If I take the simple example here: http://elm-lang.org/examples/buttons, the line:

type Msg = Increment | Decrement

defines a union type Msg as "being" either Increment or Decrement. It seems to suggest that Increment and Decrement are types too. What are they exactly? (They're not defined elsewhere in the example, nor are they predefined types).

Then, they are used in the view function as an argument of onClick. Now, they seem to act like a kind of "message" (whatever that means). In JS, this would probably be achieved by assigning a value to a (mutable) variable in each case -- which of course can't be the Elm way. So, is the way types work related to the topic of immutability?

The view function:

view model =
  div []
    [ button [ onClick Decrement ] [ text "-" ]
    , div [] [ text (toString model) ]
    , button [ onClick Increment ] [ text "+" ]
    ]

I think this potentially opens a broader topic (if someone can point to useful links, thanks!) but my question is: what are Increment and Decrement here? How do they fit in Elm's type system?

like image 352
Nicolas Le Thierry d'Ennequin Avatar asked Oct 18 '22 00:10

Nicolas Le Thierry d'Ennequin


1 Answers

Increment and Decrement are data constructors. You can think of them as OO constructors, they can have parameters and more importantly, one can tell them apart.

You are correct that they are indeed a message; but since they have no parameters, they are no different from enumeration values. The fact that a value is immutable has little to do with it. C/C++/Java also support enumerations.

In this specific case, you can even think of Msg as fancy names for a boolean.

Sum types are actually mostly like union types in C. The difference is that in Elm it stores which of the options it is. Elm takes these concepts from Haskell.

like image 114
Jan Groothuijse Avatar answered Oct 29 '22 15:10

Jan Groothuijse