TL;DR
In Elm Static Types, we discussed why Elm is a statically typed language. Today we talk about important feature, Elm type annotations. This post is part of the functional language series, and it is based on a remarkable book Programming Elm Build Safe and Maintainable Front-End Applications by Jeremy Fairbank.
We have already talked about Elixir type annotations. This is done using @spec
module attribute. In Elm, you can also state variable and function input/output type annotations. Type annotations are not mandatory, but they make your code more readable and less confusing. Also, some tools use type annotation for generating documentation.
We added three variables along with type annotations: String, Float, and Boolean. The type in annotation starts with uppercase. After compilation and running index.html, we still see the same greeting String.
If we change line 13 with:
main = text planck
Compile fails:
Let’s annotate functions:
We added function that has as input String and returns String. This is why we have `String -> String` annotations. You can think of it as String is transformed into String.
Let’s see how annotations really help compiler to prevent errors in runtime. We create functions with two input parameters of mix types, String
and Int
.
This is an application that has run time bug. When we compile this application and open index.html, we get Karlo has 2 legs.
But function does not report an error for:
main = text (numberOfLegs "Karlo" True)
We get Karlo has True legs.
From a user perspective, this is clearly a bug. But with type annotations, Elm compiler caught the error.
Compiler output:
The cheapest bug is bug caught as early as possible. Compile-time is an excellent moment to detect bugs.
For a function with two arguments, we have the following type annotation:
String -> ( Int -> String)
Here we have a function that has for input String and that returns a function that has Int as input and that returns String. Remember that Elm functions are curried. What is the first curried function in numberOfLegs?
Remember
- the purpose of type annotation
- naming convention
- how to annotate variable and function
- the benefit of type annotations
- caught bug early in development