๐Ÿ’Basic types

Elixir supports the basic types like:

  1. Integer

  2. Float

  3. Boolean

  4. Atom

  5. String

x = 1        # integer
x = 0.5      # float
x = true     # boolean
x = :atom    # atom
x = "elixir" # string

Arithmetic

To perform arithmetic on numbers, you can use the following operators:

  1. +: addition

  2. *: multiplication

  3. /: floating point division

  4. -: subtraction

  5. div(dividend, divisor): integer division, truncates the floating point (if any)

  6. rem(dividend, divisor): remainder of division (similar to % in other languages)

There are also some notable utility functions like:

  1. round(number): rounds a number to the closest integer

  2. trunc(number): retrieves only the integer part of a float

  3. is_integer(value): returns if given value is an integer (floats do not count as integers)

  4. is_float(value)

  5. is_number(value)

There are also other modules from Erlang like :math that provide additional utility functions such as pow(x, y) and sqrt(x).

Booleans

Elixir supports true and false as boolean types (much like many other languages):

Boolean operators are also supported such as or/2, and/2, and not/1:

These operators are short circuit operators. This means that the right hand side is executed iff the left hand side is insufficient to determine the result:

nil values

nil in Elixir represents the absence of a value (similar to null in other languages). nil and false are both considered "falsy" values (i.e. evaluates to false) and all other values are considered "truthy".

To operate with booleans and nil values, additional operators are supported: ||/2, &&/2, !/1 that correspond to and, or, and not.

Atoms

An atom is a constant whose value is its own name. They are globally unique so :apple == :apple. The most common use case for atoms is to signal the return value of a function such as :ok or :error.

Strings

Much like other languages like Java, strings are denoted using double quotes.

String concatenation is achieved using <>/2:

String interpolation (i.e. string templates/string formatting) is achieved by adding #{} into the string with the variable/expressions going within the curly braces:

All values are converted to a string in string interpolation

You can print to the console using IO.puts/1 like System.out.println().

To retrieve the length of a string, use the String.length/1 function. The String module contains many more string manipulation functions.

Structural comparison

You can compare between two values using ==, !=, <=, >=, <, and > operators.

Notice that although we were comparing an integer to a float, the result is still true. This can be mitigated by using the strict comparison operators, === and !==:

Last updated