Compiler Reminders

https://news.ycombinator.com/rss Hits: 5
Summary

Even though it is rarely called that way, compiler reminders are a very useful feature in Elm, one that is core to making Elm code maintainable.The idea is that whenever a change in the code would lead to other code needing to be modified at the same time, we'd get a compiler error reminding us that we need to make some kind of change.We like this so much in Elm that a common task for beginners is to take the basic Elm counter example and add a button to reset the counter to 0. This usually goes well (depending on how much the different syntax bothers them) because the compiler will tell them what the next step is.(I'll go through it so if you want to do it yourself, pause now and have a go at it)We add a button: button [ onClick Reset ] [ text "Reset" ] somewhere in the view.-- NAMING ERROR --------------------------------------------------- src/Main.elm I cannot find a `Reset` variant: 38| , button [ onClick Reset ] [ text "Reset" ] ^^^^^ We get a compiler error saying that the Reset value is unknown, so we add it to the list of variants for the Msg type.type Msg = Increment | Decrement | Reset-- MISSING PATTERNS ----------------------------------------------- src/Main.elm This `case` does not have branches for all possibilities: 25|> case msg of 26|> Increment -> 27|> { model | count = model.count + 1 } 28|> 29|> Decrement -> 30|> { model | count = model.count - 1 } Missing possibilities include: Reset I would have to crash if I saw one of those. Add branches for them! We get a compiler error saying that the update function does not have a branch for the Reset variant (because of the compiler's exhaustiveness checking), so we add the branch where the counter is set to 0.update : Msg -> Model -> Model update msg model = case msg of -- ...other branches... Reset -> { model | count = 0 }And the feature is then complete!We added one piece of code, got 2 compiler errors that required more changes—and more or less indicated how to resolve the issue—and once we did, eve...

First seen: 2025-04-27 13:16

Last seen: 2025-04-27 17:16