A common clerical mistake which Elm, Reason etc. prevents, is when we grab something from a list and pass it to another function. What if in a rare case it is possible that the element doesn't exist? A function deeper in the stack might crash, or if defensively built, substitute it with an empty value. Both could be wrong.
By providing more information about our data and our functions to the compiler, the compiler can ensure our code always follow those constraints. These constraints are often in our head when using dynamically typed languages, or even statically typed OO languages. Typed FP helps us make them explicit in code so the compiler can track it instead of we tiring ourselves mentally and making a mess of it.
I’m curious about this comment on statically typed OO languages. I work mainly with C# and don’t have much FP experience. Are you referring to exhaustive matching?
Edit: To clarify, I understand that C# compiler won’t prevent you from trying to access an element in an empty collection. What prevents you, in a typed FP language, from accessing head of an empty list?
In OCaml, (List.hd []) throws an exception, which is not a desirably behaviour, so we mostly use a safer version of List.hd which would return an option type. This could be either "None" or "Some(value)". To operate on option types, we have to pattern match and handle both cases where the value could be either None or Some)
Exhaustive pattern matching is useful here, so is the very notion of variants. Without variants (or sum type / union type) we tend to leave domain concepts implicit in the codebase. While we can simulate variants with classes, it is too unwieldy to be used except for core domain concepts.
I didn't think so. So claims like:
> In my experience, Elm code is only ever in a state of "horribly broken, won't compile" or "works".
Which I find to be pretty common among fans of strongly typed functional languages, is incorrect.
But, state errors are caught – your application can not get into an impossible state and therefore should never have any runtime errors.
Getting back to logical errors – Elm can provide some additional safeguards. For example you could have a record
``` type alias Point = { x: Int, y: Int } ```
and then decode it with
``` decode.map2 Point (field "y" int) (field "x" int) ```
Whoops you got the wrong order.
So you could make X and Y explicit types:
``` type alias Point = { x: PointX, y: PointY } type PointX = PointX Int type PointY = PointY Int decode.map2 Point (field "x" decodeX) (field "y" decodeY) ```
Now your decoder won't compile unless the types line up correctly. But this adds a bit of extra overhead in unwrapping the values, but not much.
Not saying you can't break an elm program. But you won't run into runtime exceptions in elm, by design:)