Understanding types in Elm

Once you've got Elm installed on your machine, you'll have a number of tools available to you. The first we'll look at is the Elm REPL (pronounced repple). Open it up by entering elm-repl in a Terminal window.

Elm REPL

Now you can type Elm code right in the Terminal. Try entering in an expression like 2 + 2. After pressing enter, the Elm compiler will evaluate your expression and print out the result for you. The result of 2 + 2 ends up being 4 : number.

REPL stands for Read-Eval-Print Loop. It reads the code you input, evaluates it, prints out the result, and then the process repeats until you type :exit.

Types in Elm

When you enter something in the REPL, you get some additional information on top of the value of your expression. When we entered 2 + 2, not only did we get the value 4, but we also got a description of our value--it's a number. If you enter a string of characters like "hello" (making sure to wrap it in double quotes), you'll see that it is a String.

This extra information is called a type signature. These types signatures are available to us thanks to the Elm compiler. For each value it comes across, the compiler keeps track of its type. This helps it catch mistakes in our code before they can make their way to our users.

Try adding 2 + "hello" and you'll see what I mean.

Hints from the compiler

Addition is an operation between numbers--not numbers and strings--so this can only be a mistake. If our program tried adding a number to a string, it would either break or give us a result that doesn't make sense. Thus, when the Elm compiler checks the types of the values we're trying to add, it halts compilation and gives us an error message.

> 2 + "hello"
-- TYPE MISMATCH --------------------------------------------- repl-temp-000.elm

The right argument of (+) is causing a type mismatch.

4│   2 + "hello"
         ^^^^^^^
(+) is expecting the right argument to be a:

    number

But the right argument is:

    String

Hint: To append strings in Elm, you need to use the (++) operator, not (+).
<http://package.elm-lang.org/packages/elm-lang/core/latest/Basics#++>

Some compilers might just stop compiling and leave you to figure out the problem on your own, but the Elm compiler is super friendly. It highlights the exact point in your code where it sees the problem, and even gives you some hints as to how you might fix it. If you've ever dealt with debugging in JavaScript, you'll come to appreciate these error messages a whole lot.

The key to understanding Elm code

Beyond being useful for the compiler, this type system is essential to understanding both the Elm documentation and other people's code. This makes them a good starting-point on our journey to making a working web app.

Let's use type-checking in the Elm REPL to learn about the basic types of values we'll be working with as we move forward.

results matching ""

    No results matching ""