3.6

Expression

Before we attempt to understand what an expression is in Elm, let’s look at its definition in algebra first. An expression groups together numbers, symbols, and operators to compute a value. Here is an example:

The expression above can be evaluated to some value depending on what x holds. Since x is a variable, its value will also change depending on the context of a problem. If x is 2, the expression will evaluate to 1. If x is 3, the expression will evaluate to 4. But what if we put a constraint on x like this:

Because the expression on the left must evaluate to 7, x can now have only one value: 4. We put a constraint on the value of a variable through an equation. Notice that we have labeled 7 on the right side of the equation as an expression too. We don’t need to have a symbol and an operator to create a valid expression. Anything that evaluates to a value is an expression. Since 7 is already a value and doesn’t need further evaluation, it’s considered an expression as well.

With this foundational knowledge about expressions, variables, and equations, let’s turn our attention back to Elm. Each line of code we have typed in the repl so far is an expression. All of them evaluate to a value. Like algebra, if we just type a number without any operator in the repl, Elm treats it as an expression and attempts to evaluate it. But since a number itself is a value, Elm doesn’t need to evaluate it any further. So it just prints the number back.

> 42
42

> 5
5
Back to top
Close