Core Language

This section will walk you through Elm’s simple core language.

This works best when you follow along, so after installing, start up elm-repl in the terminal. (Or use the online REPL.) Either way, you should see something like this:

  1. ---- elm repl 0.18.0 -----------------------------------------------------------
  2. :help for help, :exit to exit, more at <https://github.com/elm-lang/elm-repl>
  3. --------------------------------------------------------------------------------
  4. >

The REPL prints out the type of every result, but we will leave the type annotations off in this tutorial for the sake of introducing concepts gradually.

We will cover values, functions, lists, tuples, and records. These building blocks all correspond pretty closely with structures in languages like JavaScript, Python, and Java.

Values

Let’s get started with some strings:

  1. > "hello"
  2. "hello"
  3. > "hello" ++ "world"
  4. "helloworld"
  5. > "hello" ++ " world"
  6. "hello world"

Elm uses the (++) operator to put strings together. Notice that both strings are preserved exactly as is when they are put together so when we combine "hello" and "world" the result has no spaces.

Math looks normal too:

  1. > 2 + 3 * 4
  2. 14
  3. > (2 + 3) * 4
  4. 20

Unlike JavaScript, Elm makes a distinction between integers and floating point numbers. Just like Python 3, there is both floating point division (/) and integer division (//).

  1. > 9 / 2
  2. 4.5
  3. > 9 // 2
  4. 4

Functions

Let’s start by writing a function isNegative that takes in some number and checks if it is less than zero. The result will be True or False.

  1. > isNegative n = n < 0
  2. <function>
  3. > isNegative 4
  4. False
  5. > isNegative -7
  6. True
  7. > isNegative (-3 * -4)
  8. False

Notice that function application looks different than in languages like JavaScript and Python and Java. Instead of wrapping all arguments in parentheses and separating them with commas, we use spaces to apply the function. So (add(3,4)) becomes (add 3 4) which ends up avoiding a bunch of parens and commas as things get bigger. Ultimately, this looks much cleaner once you get used to it! The elm-html package is a good example of how this keeps things feeling light.

If Expressions

When you want to have conditional behavior in Elm, you use an if-expression.

  1. > if True then "hello" else "world"
  2. "hello"
  3. > if False then "hello" else "world"
  4. "world"

The keywords if then else are used to separate the conditional and the two branches so we do not need any parentheses or curly braces.

Elm does not have a notion of “truthiness” so numbers and strings and lists cannot be used as boolean values. If we try it out, Elm will tell us that we need to work with a real boolean value.

Now let’s make a function that tells us if a number is over 9000.

  1. > over9000 powerLevel = \
  2. | if powerLevel > 9000 then "It's over 9000!!!" else "meh"
  3. <function>
  4. > over9000 42
  5. "meh"
  6. > over9000 100000
  7. "It's over 9000!!!"

Using a backslash in the REPL lets us split things on to multiple lines. We use this in the definition of over9000 above. Furthermore, it is best practice to always bring the body of a function down a line. It makes things a lot more uniform and easy to read, so you want to do this with all the functions and values you define in normal code.

Note: Make sure that you add a whitespace before the second line of the function. Elm has a “syntactically significant whitespace” meaning that indentation is a part of its syntax.

Lists

Lists are one of the most common data structures in Elm. They hold a sequence of related things, similar to arrays in JavaScript.

Lists can hold many values. Those values must all have the same type. Here are a few examples that use functions from the List library:

  1. > names = [ "Alice", "Bob", "Chuck" ]
  2. ["Alice","Bob","Chuck"]
  3. > List.isEmpty names
  4. False
  5. > List.length names
  6. 3
  7. > List.reverse names
  8. ["Chuck","Bob","Alice"]
  9. > numbers = [1,4,3,2]
  10. [1,4,3,2]
  11. > List.sort numbers
  12. [1,2,3,4]
  13. > double n = n * 2
  14. <function>
  15. > List.map double numbers
  16. [2,8,6,4]

Again, all elements of the list must have the same type.

Tuples

Tuples are another useful data structure. A tuple can hold a fixed number of values, and each value can have any type. A common use is if you need to return more than one value from a function. The following function gets a name and gives a message for the user:

  1. > import String
  2. > goodName name = \
  3. | if String.length name <= 20 then \
  4. | (True, "name accepted!") \
  5. | else \
  6. | (False, "name was too long; please limit it to 20 characters")
  7. > goodName "Tom"
  8. (True, "name accepted!")

This can be quite handy, but when things start becoming more complicated, it is often best to use records instead of tuples.

Records

A record is a set of key-value pairs, similar to objects in JavaScript or Python. You will find that they are extremely common and useful in Elm! Let’s see some basic examples.

  1. > point = { x = 3, y = 4 }
  2. { x = 3, y = 4 }
  3. > point.x
  4. 3
  5. > bill = { name = "Gates", age = 57 }
  6. { age = 57, name = "Gates" }
  7. > bill.name
  8. "Gates"

So we can create records using curly braces and access fields using a dot. Elm also has a version of record access that works like a function. By starting the variable with a dot, you are saying please access the field with the following name. This means that .name is a function that gets the name field of the record.

  1. > .name bill
  2. "Gates"
  3. > List.map .name [bill,bill,bill]
  4. ["Gates","Gates","Gates"]

When it comes to making functions with records, you can do some pattern matching to make things a bit lighter.

  1. > under70 {age} = age < 70
  2. <function>
  3. > under70 bill
  4. True
  5. > under70 { species = "Triceratops", age = 68000000 }
  6. False

So we can pass any record in as long as it has an age field that holds a number.

It is often useful to update the values in a record.

  1. > { bill | name = "Nye" }
  2. { age = 57, name = "Nye" }
  3. > { bill | age = 22 }
  4. { age = 22, name = "Gates" }

It is important to notice that we do not make destructive updates. When we update some fields of bill we actually create a new record rather than overwriting the existing one. Elm makes this efficient by sharing as much content as possible. If you update one of ten fields, the new record will share the nine unchanged values.

Comparing Records and Objects

Records in Elm are similar to objects in JavaScript, but there are some crucial differences. The major differences are that with records:

  • You cannot ask for a field that does not exist.
  • No field will ever be undefined or null.
  • You cannot create recursive records with a this or self keyword.

Elm encourages a strict separation of data and logic, and the ability to say this is primarily used to break this separation. This is a systemic problem in Object Oriented languages that Elm is purposely avoiding.

Records also support structural typing which means records in Elm can be used in any situation as long as the necessary fields exist. This gives us flexibility without compromising reliability.