๐Basic types
Elixir supports the basic types like:
Integer
Float
Boolean
Atom
String
x = 1 # integer
x = 0.5 # float
x = true # boolean
x = :atom # atom
x = "elixir" # stringArithmetic
To perform arithmetic on numbers, you can use the following operators:
+: addition*: multiplication/: floating point division-: subtractiondiv(dividend, divisor): integer division, truncates the floating point (if any)rem(dividend, divisor): remainder of division (similar to%in other languages)
There are also some notable utility functions like:
round(number): rounds a number to the closest integertrunc(number): retrieves only the integer part of a floatis_integer(value): returns if givenvalueis an integer (floats do not count as integers)is_float(value)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:
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