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?
Msgis not used elsewhere in the example. Does it have to be defined this way just so we are allowed to use thecasestatement in theupdatefunction? - Nicolas Le Thierry d'EnnequinMsganywhere else because the other functions aren't annotated in this example (in Elm they don't have to be but it can be very helpful to annotate your functions). AssumingModelis a type alias ofInt, the type annotations should be:view : model -> Html Msgandupdate : Msg -> Model -> Model- Chad Gilbertview : Model -> Html Msg? - Nicolas Le Thierry d'EnnequinModel. StackOverflow won't let me change it now. Good catch. It will still compile with lowercase but it has a different meaning. Lowercase in the annotation means roughly anything can go in there but you'd typically see something likeaorb, as inview : a -> Html Msg(by way of convention) - Chad Gilbert