In this post we will learn a little bit about Elixir basic types, strings, atoms, integers, float, booleans, lists and tuples. I will be using Elixir 1.0.2 . To install Elixir you can access the installation guide on Elixir documentation, http://elixir-lang.org/install.html.
We will be starting by using the REPL console that comes bundled with Elixir. So lets get started.
Strings
Strings in Elixir are inserted between double quotes:
iex> "Hello World"
"Hello World"
We can use multi-line strings:
iex> """
I'm a multi-line
string
"""
Atoms
Atoms are just like symbols in Ruby. They consist of a colon, followed by letters, digits, and underscores.
:foo
:bar
:hello@world
:”Hello Elixir World”
:this_is_a_short_sentence
In Elixir, atoms are used frequently to tag response types.
Numbers
Integers
Integers can be written in various ways, let’s see that:
9876789
1_000_000
2_123 == 2123 #Like in Ruby we can use underscores to make numbers easier to read
Float Points
Floating point numbers have a decimal point.
1.78
0.56
Booleans
In Elixir, everything, excepting “false” and “nil” it’s true. “false” and “nil” are both alias to the atoms with the same name, :false and :nil.
iex>:false == false
true
iex>nil == :nil
true
Lists
Lists are stored in memory as linked lists, meaning that each element in a list holds its value and points to the following element until the end of the list is reached.
[1,2,3]
[:foo, :bar]
[:bar, 1, [2,3,4], :foo]
Two lists can be concatenated and subtracted with ++/2 and –/2 operators.
iex> [1,2,3] ++ [4,5,6]
[1, 2, 3, 4, 5, 6]
iex> [1, true, 2, false, 3, true] **--** [true, false]
[1, 2, 3, true]
We can access the head and the tail of a list as follows:
iex> [head | tail ] = [1, 2]
iex> head
1
iex> tail
2
Note:
Functions in Elixir are identified by name and by number of arguments (i.e. arity). Therefore, is_boolean/1 identifies a function named is_boolean that takes 1 argument.is_boolean/2 identifies a different (nonexistent) function with the same name but different arity. — *http://elixir-lang.org/
Tuples
Tuples, on the other hand, are stored contiguously in memory.
iex> {1, 2, 3}
{1, 2, 3}
iex> {:ok, "hello"}
{:ok, "hello"}
We can access a Tuple element with:
iex> elem({:ok, "Hello"}, 1)
"Hello"
And the tuple size with:
iex> tuple_size({:ok, "Hello"})
2
Note:
Tuples are used very frequently in Pattern Matching and in return values from various functions. In the next posts we will talk a little more about it
Resources
Basic types – Elixir
In this chapter we will learn more about Elixir basic types: integers, floats, booleans, atoms, strings, lists and…elixir-lang.org
Starting Out (for real) | Learn You Some Erlang for Great Good!
Erlang’s basics explained: numbers, atoms, boolean algebra and comparison operators, tuples, lists, list comprehensions…learnyousomeerlang.com
We want to work with you. Check out our "What We Do" section!