Skip to content

CS Basic Operators

suryapratapmehra edited this page Feb 7, 2018 · 4 revisions

Basic Arithmetic

+, -, * work as expected. However, the / operator always returns a float.

a = 4
b = 5
a + b # 9
a - b # -1
a * b # 20
a / b # 0.8

For integer division and getting the remainder we can use the div/2 and the rem/2 functions.

a = 4
b = 5
div(a, b) # 0
rem(a, b) # 4

Lists and Strings

For concatenation of strings we can use the <> operator.

str = "foo" <> "bar"
IO.puts(str) # foobar

For manipulating lists we use the ++ and -- operators.

list = [1, 2, 3]
list ++ [4, 5, 6] # [1, 2, 3, 4, 5, 6]
list -- [2] #[1, 3]

Boolean Operators

Elixir provides ||, && and ! which accepts arguments of any type and hence preferred over and, or and not. For these operators, all values except false and nil evaluate to true.

# or
1 || true #1
false || 11 #11

# and
nil && 13 #nil
true && 17 #17

# !
!true #false
!1 #false
!nil #true
1 && 0 # 0
2 && -1 # -1
false && -1 # false (short circuiting)
true or 1 # true (short circuiting)

Comparison Operators

Elixir also provides ==, !=, ===, !==, <=, >=, < and > as comparison operators:

1 == 1 #true
1 != 2 #true
1 < 2 #true

The difference between == and === is that the latter is more strict when comparing integers and floats:

1 == 1.0 #true
1 === 1.0 #false

In elixir we can compare two different data types. The reason we can compare different data types is pragmatism. Sorting algorithms don’t need to worry about different data types in order to sort. The overall sorting order is defined below:

number < atom < reference < function < port < pid < tuple < map < list < bitstring

1 < :atom #true