3.2

Simple Arithmetic

Performing arithmetic calculations in Elm is straightforward. We can even use it as a calculator if we want. From the terminal, go to the beginning-elm directory and run elm-repl command to launch the repl. Now let’s try some simple arithmetic.

> 1 + 2
3 : number

> 4534 - 789
3745 : number

> 42 * 10
420 : number

> 9 / 4
2.25 : Float

There are two types of divisions in Elm: floating-point and integer. The / operator is used for the former and // for the latter. The integer division truncates everything after the decimal point.

> 5 / 2
2.5 : Float

> 5 // 2
2 : Int

For the rest of this chapter, the type annotations printed by the repl (e.g., : Float) will be omitted to reduce the clutter. We haven’t covered types yet. So they won’t make much sense now anyway. We will cover them in chapter 4.

Similar to mathematics, we place the operators (+, -, *, and /) between the numberical arguments. This is called infix style. We can also write them in prefix style, where the operator precedes its arguments. Prefix style requires us to enclose the operator in parentheses.

> (+) 1 2
3

> (-) 4534 789
3745

> (*) 42 10
420

> (/) 9 4
2.25

Operator precedence

We can also use several operators in one line.

> 42 * 200 - 8000
400

> (42 * 200) - 8000
400

> 42 * (200 - 8000)
-327600

Notice how in the last example above we used parentheses to change the order in which the operators are applied. * has a higher precedence than -. Therefore, if we want - to be applied first, we must apply parentheses around its arguments. In the second example, we made the precedence explicit by applying parentheses around *, but it’s not necessary.

Elm assigns numeric precedence values to operators, with 0 being the lowest precedence and 9 being the highest. A higher-precedence operator is applied before a lower-precedence operator. See the table below to find the precedence for various operators in Elm.

Associativity

Associativity determines whether an expression containing multiple operators is evaluated from left to right, or right to left. Operators that evaluate from left are called left-associative and the ones that evaluate from right are called right-associative. +, -, *, and / are all left-associative. Whereas the power operator (^) is right-associative.

> 2 ^ 3 ^ 2
512

> (2 ^ 3) ^ 2
64

If we don’t use parentheses, the power operator evaluates the expression from right to left. The table below shows the precedence and associativity of various operators in Elm. The operators you see here that haven’t been covered yet will be discussed in later parts of the book.

Operators Precedence Associativity
>> 9 left
<< 9 right
^ 8 right
* / // % rem 7 left
+ - 6 left
++ :: 5 right
== /= < > <= >= 4 none
&& 3 right
|| 2 right
|> 0 left
<| 0 right

Source: Unofficial FAQ for the Elm language

Back to top

New chapters are coming soon!

Sign up for the Elm Programming newsletter to get notified!

* indicates required
Close