We're live-coding on Twitch! Join us!
Elixir Crash Course

Elixir Crash Course

Elixir Crash Course

In this tutorial, we will look briefly at a few basic aspects of Elixir. It is important you know that this tutorial cannot teach you to call that you need to know about Elixir. As you follow along, do well to try out the codes snippet so you have a feel of how it works.

Introducing Elixir

Table of Contents

Elixir is a dynamic, functional language designed for building scalable and maintainable applications.

It leverages the Erlang VM, known for running low-latency, distributed and fault-tolerant systems, while also being successfully used in web development and the embedded software domain. Elixir is an open source project, originally started by José Valim. The source code can be found on the GitHub repository at https://github.com/elixir-lang/elixir.

Installing Elixir

Installing Elixir varies depending on the operating system your machine uses. The most up-to-date instruction on installing Elixir can be found on the official guide. Go ahead and install it.

The Interactive Shell

To test, if your installation was successful, you can start an interactive Elixir session. Open up your terminal and run the command iex.

$ iex

Erlang/OTP 19 [erts-8.0] [source] [64-bit] [smp:2:2] [async-threads:10] [kernel-poll:false]

Interactive Elixir (1.3.0) - press Ctrl+C to exit (type h() ENTER for help)
iex(1)> 

Your version number may be different from my own.

The best way to learn about the features of Elixir is by making use of the interactive shell.

Running iex starts an instance of the BEAM and an interactive Elixir shell inside it. Runtime information such as the versions of Elixir and Erlang are shown, as you can see above. The prompt is provided so you can enter Elixir expressions.

iex(1)> 7 + 2 # Expression
9             # Return Value
iex(2)>       # iex Prompt

After typing an expression, it is interpreted and executed. The return value is then printed to the screen. Whatsoever returns a value is an expression in Elixir. You can enter expressions that go beyond one line. When you do so, iex prompts for the additional lines with an ellipsis (...). The expression does not get evaluated till it gets to the end.

iex(1)> 9 -       # Beginning of expression
...(1)> 4 +       
...(1)> 2 * (
...(1)> 6 - 3
...(1)> )         # End of expression
11
iex(2)> 

In Elixir, a line break indicates the end of an expression. There is no need for a special character or column to indicate that. It is also possible to add more than one expression in a single line. When you do so, the return value is the result of the last expression. See it below:

iex(2)> 9+4; 5*2
10                # Result of the last expression    
iex(3)>  

To exit from iex, just hit CTRL+C twice.

IEx Helper

One of the basic and important thing you can get from the interactive shell is offered by the iex helper. You get this when you run h in an Elixir session.

iex(1)> h

                           IEx.Helpers                            

Welcome to Interactive Elixir. You are currently seeing the
documentation for the module IEx.Helpers which provides many
helpers to make Elixir's shell more joyful to work with.

This message was triggered by invoking the helper h(), usually
referred to as h/0 (since it expects 0 arguments).

You can use the h function to invoke the documentation for any
Elixir module or function:

┃ h Enum
┃ h Enum.map
┃ h Enum.reverse/1

You can also use the i function to introspect any value you have
in the shell:

┃ i "hello"

There are many other helpers available:

  • b/1           - prints callbacks info and docs for a
    given module
  • c/1           - compiles a file into the current
    directory
  • c/2           - compiles a file to the given path
  • cd/1          - changes the current directory
  • clear/0       - clears the screen
  • flush/0       - flushes all messages sent to the shell
  • h/0           - prints this help message
  • h/1           - prints help for the given module,
    function or macro
  • i/1           - prints information about the given data
    type
  • import_file/1 - evaluates the given file in the shell's
    context
  • l/1           - loads the given module's beam code
  • ls/0          - lists the contents of the current
    directory
  • ls/1          - lists the contents of the specified
    directory
  • nl/2          - deploys local beam code to a list of
    nodes
  • pid/1         - creates a PID from a string
  • pid/3         - creates a PID with the 3 integer
    arguments passed
  • pwd/0         - prints the current working directory
  • r/1           - recompiles the given module's source file
  • recompile/0   - recompiles the current project
  • respawn/0     - respawns the current shell
  • s/1           - prints spec information
  • t/1           - prints type information
  • v/0           - retrieves the last value from the history
  • v/1           - retrieves the nth value from the history

Help for all of those functions can be consulted directly from
the command line using the h helper itself. Try:

┃ h(v/0)

To learn more about IEx as a whole, just type h(IEx).

iex(2)> 

You can get the documentation of different Elixir module. This will come in handy for you can you make progress. So do well it always remember it.

Variables

In Elixir, you don’t explicitly declare a variable or its type. The variable type is dependent on the data it currently contains. This is because Elixir is a dynamic programming language.In Elixir, an assignment is called binding. In other languages such as Ruby, you assign a variable to a value. That is not how it works in Elixir world. In Elixir, you bind a variable to a value.

iex(1)> age = 35  # Binds the variable age to the integer 35
35                # Returns the result of the last expression

As I said earlier, every expression in Elixir has a result. In this case, the result is whatever is on the right side of the = operator. After binding a variable to a value, you can now reference the value.

iex(2)> age
35

In Elixir, only alphanumerics and underscores are allowed when naming a variable. It is important that a variable name only starts with a lower alphabet or an underscore. Thus valid variable names include the following:

_my_age
location_id
address
class13

While invalid variable names include:

Distance
speed!
13value

Comments

Comments in Elixir starts with the # character. This shows that the line after it is a comment. Block comments are not supported in Elixir.

Elixir Types

Numbers

Numbers are either integers or floats.Examples include:

758   # Integer
0x1F  # Float
68.1  # Float

Numbers work as you will expect. Numeric operations can be performed on them.

iex(1)> 6 * 5 + 3
33 

Atoms

Atoms are constants representing something’s name. In Ruby, they are known as symbols. Atoms start with a colon character, followed by alphanumerics and/or underscore characters. You can also create atoms containing arbitrary characters by enclosing the characters following the colon in double quotes. It may end with an exclamation point or a question mark. Two atoms with the same name will always be equal. An atom’s name is its value. Examples of atoms include:

:"this atom is valid"
:name
:user_address
:is_valid?

Tuples

Tuples are ordered collections of values. You write tuples between braces, separated by a comma. Tuples are effective in pattern matching (which is outside the scope of this tutorial). Examples of tuples include:

{ "John", 19 }
{ :status, 200, "www.scotch.io"}

Lists

Lists are used to manage dynamic, variable-sized collections of data. You may think lists are like arrays in other languages, but they are not. Though the syntax resembles arrays from other languages. Examples include:

[1,2,3,4]
["Dan", "John", "Doe"]

Operations can be performed on lists.

iex(1)> [ 1, 2, 3 ] ++ [ 7, 8, 9 ]  # concatenation
[1, 2, 3, 7, 8, 9]
iex(2)> [1, 2, 3, 4] -- [2, 4]      # difference
[1, 3]
iex(3)> 1 in [5, 3, 2, 1]           # membership
true

Keyword List

Situations will always arise where you will need key/value pairs. Elixir has you covered with keyword lists. Here is what keyword lists look like:

iex(1)> [name: "John", age: 29, gender: "male"]
[name: "John", age: 29, gender: "male"]

Maps

A map is a collection of key/value pairs. A map is created using the %{} syntax. A map always looks like this:

%{ key => value, key => value }

Here is an example showing how to create a map:

iex(1)> john = %{:name => "John", :age => 29, :gender => "male"}
%{age: 25, name: "John", gender: "male"}

Here is another way of writing the above (if the keys are atoms);

iex(2)> john = %{name: "John", age: 29, gender: "male"}
%{age: 29, gender: "male", name: "John"}

Strings

Elixir has two kinds of string: single-quoted and double-quoted. They differ significantly in their internal representation.

iex(5)> "Here is an example of a string"
"Here is an example of a string"
iex(6)> 'Here is another string'
'Here is another string'

There are Heredocs syntax with supports better formatting for multi-line strings. Example:

iex(3)> """
...(3)> Here is a multi-line string
...(3)> It goes further down
...(3)> Lets end here 
...(3)> """
"""\nHere is a multi-line string\nIt goes further down\nLets end here\n"""

As you can see above, I started and ended the heredoc with triple double-quotes. It is important to know that these triple double-quotes must be on their own lines. Strings can also be concatenated using the <> operator.

iex(4)> "Hello" <> " world"
"Hello world"

It is that simple!

Operators

Elixir has a very rich set of operators. The arithmetic operators include the standard + , - , * , and /. They work as you will expect. Next we have the comparison operators.

===, !==      # Strict equality/inequality
==, !=        # Weak equality/inequality
<, >, <=, >=  # Less than, greater than,

Here is an example of how weak and strict operators work, try them in your shell to have a feel of it.

iex(1)> 9 == 9
true
iex(2)> 9 == 9.0
true
iex(3)> 9.0 == 9.0
true
iex(4)> 9 === 9
true
iex(5)> 9 === 9.0
false
iex(6)> 9.0 === 9.0
true

Here are links to awesome resources that will help you become a better Elixir developer. Feel free to recommend other resources in the comment section.

Conclusion

Going forward, you have the foundational knowledge to dive deep into Elixir. I hope you enjoyed it.