Operators
Learn about different kinds of Elixir operators and their usage.
We'll cover the following
An operator is used to manipulate individual data items and return a result. These items are called operands or arguments. Operators are represented by special characters or keywords.
For example, the multiplication operator is represented by an asterisk (*
). Elixir has a very rich set of operators. Here’s a list of all operators that Elixir is capable of parsing, ordered from higher to lower precedence, alongside their associativity:
- Comparison operators
- Boolean operators
- Relaxed boolean operators
- Arithmetic operators
Let’s cover them in detail.
Comparison operators
-
a===b
shows the strict equality (so1 === 1.0
isfalse
). -
a!==b
shows strict inequality (so1 !== 1.0
istrue
). -
a==b
shows value equality (so1 == 1.0
istrue
). -
a!=b
shows value inequality (so1 != 1.0
isfalse
). -
a>b
shows the value is greater than the other (so2>1
istrue
). -
a>=b
shows the value is greater than or equal to the other (so2>=1
istrue
). -
a<b
shows the value is less than the other (so1<2
istrue
). -
a<=b
shows the value is less than or equal to the other (so1<=2
istrue
).
The ordering comparisons in Elixir are less strict than in many languages, as we can compare values of different types. If the types are the same or are compatible (for example, 3 > 2
or 3.0 < 5
), the comparison uses natural ordering. Otherwise comparison is based on type according to this rule: number < atom < reference < function < port < PID < tuple < map < list < binary.
Boolean operators
These operators expect true
or false
as their argument.
-
a or b
-
a and b
-
not a
Relaxed boolean operators
These operators take arguments of any type. Any value apart from nil
or false
is interpreted as true
. Below are relaxed boolean operators supported by Elixir:
a||b
givestrue
ifa
istrue
. Otherwise, it givesb
.a && b
givesfalse
ifa
isfalse
. Otherwise, it givesb
.!a
givesfalse
ifa
istrue
. Otherwise, it givestrue
.
Arithmetic operators
Below are arithmetic operators supported by Elixir:
-
+
is an add operator (so1+2
is3
). -
-
is a subtract operator (so2-1
is1
). -
*
is a multiplication operator (so2*1
is2
). -
/
is a division operator that gives result in float (so1/2
is0.5
). -
div
returns a quotient on division (sodiv(2,1)
is2
). -
rem
returns remainder on division (sorem(5,2)
is1
). Integer division yields a floating-point result. We usediv(a,b)
to get an integer. The remainder operator isrem
. It’s called as a function, like (rem(11, 3) => 2
).
Get hands-on with 1400+ tech skills courses.