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.

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.

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.

### Operator precedence

We can also use several operators in one line.

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.

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 |