A Beginner’s Guide to Elixir Programming Language: All You Need to Know
Are you looking for a new programming language to learn? Why not give Elixir a try? As a dynamic, functional programming language designed to build scalable and maintainable applications, Elixir can offer you an exciting new way to code.
With its focus on concurrency and fault tolerance, Elixir is an excellent choice for building applications that handle high-volume requests, such as web services and real-time data streaming.
In this beginner’s guide to Elixir, we’ll walk you through the basics of the language and explain why it might be the perfect choice for your next project. We’ll cover sub-topics like its syntax, data types, functions, modules, and more. By the end of this article, you should understand what Elixir is and how to learn it best.
So let’s get started:
What is Elixir Programming Language?
Elixir is a general-purpose, functional programming language built on top of the Erlang virtual machine (BEAM). It was created by José Valim in 2011 to bring the Erlang language’s benefits to a more modern and approachable syntax.
Valim wanted to create a new language that was easy to use and understand yet still had powerful features like the Erlang runtime. That resulted in an expressive, dynamic, and strongly typed language that is easier to read than its predecessor. It supports concurrent programming models and encourages developers to write highly maintainable and efficient code.
Elixir leverages the Erlang VM’s robust concurrency and fault-tolerance capabilities to create an ideal environment for building large, distributed applications.
What’s the Elixir Language Used For?
Elixir bills itself as a dynamic, functional language with immutable data structures and an actor-based approach to concurrency and fault tolerance. That makes it ideal for building distributed systems that process large amounts of data quickly and reliably. As such, Elixir is often used in web development, IoT applications, real-time system monitoring, and more.
Companies That Use Elixir
Elixir is a highly popular language, so it’s no surprise that many major companies have adopted it. These companies include Airbnb, Moz, Adobe, Bleacher Report, Discord, and Pinterest. That makes Elixir an excellent choice for anyone looking to develop enterprise-grade applications.
How Does One Learn Elixir?
If you’re interested in learning Elixir but aren’t sure where to start, a few resources are available online. You’ll find most of the official documentation on the Elixir website. Plenty of books cover the language in detail, such as Programming Elixir by Dave Thomas and Metaprogramming Elixir by Chris McCord.
Now, let’s see some code:
The easiest way to get started with Elixir is to use an online platform such as Exercism.org or ElixirSchool. These sites provide example exercises that will help you get to grips with the basics of the language. We also recommend checking out ElixirConf, a yearly conference dedicated to learning and sharing knowledge about the language.
Finally, don’t forget to join an online community! The Elixir Forum is a great place to ask questions and get help from experienced users. There are also plenty of other Elixir-related Slack channels, mailing lists, and IRC channels that you can join.
Installing Elixir
Elixir is one of the easier languages to install and get up and running, as it has more than a few different ways of installing it.
On Windows
Installing Elixir Using a Windows Installer
The easiest way to install Elixir on Windows is by downloading and running the Erlang Installer.
You can begin by downloading the Erlang installer here.
After that, you want to download and install the Elixir compatible with the Erlang or OTP version you’ve installed. To do this, go to Elixir’s download page and pick the most appropriate version for your system.
Here are the different versions of Elixirs:
If you’re unsure about the Erlang/OTP version you’re using, run the Erl command in the Terminal, and it should tell you what version of the OTP platform you have installed.
You can find all the previously released versions of Elixir here.
Installing Elixir Using Scoop
Scoop is a command-line installer for Windows. It can quickly and easily install Elixir and its dependencies. To do this, open the Command Prompt and type in:
scoop install erlang
scoop install elixir
Installing Elixir Using Chocolatey
Chocolatey is a package manager for Windows. To install Elixir with Chocolately, open the Command Prompt and type in:
choco install elixir
On Mac OS X
Installing Elixir Using Homebrew
Homebrew is one of the easiest and most popular ways to install Elixir on Mac OS X. To install Elixir with Homebrew, open the Terminal and type in:
brew install elixir
Installing Elixir Using Macports
MacPorts is a package manager for Mac OS X. It can quickly and easily install Elixir and its dependencies. To do this, open the Terminal and type in:
sudo port install
Installing Elixir Using Asdf
Asdf is a version manager for Mac OS X. It can quickly and easily install Elixir and its dependencies. To do this, open the Terminal and type in:
asdf install elixir
Installing Elixir on Arch Linux
On Arch Linux, Elixir can be installed using the Pacman package manager. To do this, open the Terminal and type in:
sudo pacman -S elixir
Installing Elixir on Ubuntu/Debian
Installing Elixir on Ubuntu is a bit tedious but still easy. To do this, open the Terminal and type in:
wget https://packages.erlang-solutions.com/erlang-solutions_1.0_all.deb && sudo dpkg -i erlang-solutions_1.0_all.deb
sudo apt-get update
sudo apt-get install esl-erlang
sudo apt-get install elixir
Installing Elixir on Fedora/CentOS/RedHat
On Fedora and CentOS, Elixir can be installed using the yum package manager. To do this, open the Terminal and type in:
sudo yum install erlang
sudo yum install elixir
Once Elixir is installed, you can go ahead and open the shell.
You’ll spend a lot of time in the Elixir shell, so it’s a good idea to get familiar with it. To start the shell, open the Terminal and type in:
Elixir Interactive Shell (EIT)
The Elixir Interactive Shell (EIT) is a great way to write and test Elixir Code interactively. You can input an expression there, and you’ll be provided with immediate feedback. Not that your code will be evaluated, not compiled — so it won’t be used in an actual program, but you can use it to test your ideas.
To open the EIT, open the Terminal and type in:
iex
Once you’re done with experimenting, you can exit the shell by typing ‘Ctrl + D’.
The Break Command
If you are stuck in an infinite loop, the Break command is there to help. You can use it in the EIT or even in a running program. It will cause the current process to exit and return you to the shell. To use it, just type ‘Ctrl + C’.
Helpers
Elixir has a few helpful commands that make working in the shell and writing code easier. Some of these are:
- h – Helpers – display help information
- c – Compile – compile files to bytecode
- r – Run – run or evaluate an expression from the command line
- d – Debugging – enter “debugging” mode
- l – Load – load a file or module into the current process
- s – Set breakpoints – set breakpoints in code for debugging purposes
- v – Variables/Vars – show all variables and their values.
These commands provide a great way to test and debug your code quickly.
Let’s Look at the Elixir Code
Now that we know a little about Elixir, let’s look at some code. Here is an example of a “hello world” program written in Elixir:
“`elixir
IO.puts “Hello, World!”
“`
IO.puts is a function that prints to the console. It’s like using `console.log` in JavaScript or `print()` in Python. As you can see, Elixir is easy to read and understand.
IO stands for Input/Output and is one of Elixir’s many built-in modules. Elixir also has other helpful modules for working with the file system, networking, database access, and more.
Strings in Elixir
Strings are a very important data type in programming languages, and Elixir is no exception.
Elixir uses UTF-8 encoding for all strings.
UTF stands for Universal Character Set Transformation Format and is a way to represent characters from different languages in one single encoding.
UTF-8 is a variable width encoding that uses one to four eight-bit bytes to represent a character. That allows it to support almost all characters in use today.
Double quotes surround Elixir.
For example, if you wanted to print “This is a double quote:”, you would do it like this:
“`elixir
IO.puts (“This uses a double quote”)
Atoms in Elixir
We all know atoms as the building blocks of matter. In Elixir, atoms are constants whose value are their name.
For example, the atom :hello is equal to itself:
“`elixir
:hello == :hello
true
“`
In other languages, they’re referred to as symbols.
They’re typically used to enumerate values or as identifiers.
Their Syntax:
Atoms are written as lowercase words that start with a colon (:).
For example, :cat, :dog, and :bird are all valid atoms.
You can also create atoms with spaces in them by enclosing the atom in single quotes:
“`elixir
:’this is an atom’ ==:’this is an atom’
true
“`
Atoms are usually used as labels or to store data, such as in a key-value store.
For example, you can use an atom to represent the user’s role in a system:
“`elixir
user = %{name: “John Doe”, role: :admin}
IO.puts(“John Doe is an #{user.role}”)
“`
The output would be:
“John Doe is an admin”
Atoms are also used in pattern matching and guards, two powerful features of Elixir.
Booleans
Elixir supports two boolean values: true and false.
These values are typically used in conditional statements to decide what code should run.
For example, a simple if statement would look like this:
“`elixir
if some_condition == true do
IO.puts “do something”
else
IO.puts “do something else”
end
“`
These boolean values can also be used to check if a given value is truthy or falsy. False and nil are always falsy, while everything else is truthy.
For example:
“`elixir
if nil do
IO.puts “This will not be printed”
else
IO.puts “This will be printed”
Arithmetic Operators
Elixir also supports the basic arithmetic operators ( + , – , * , and / ) for addition, subtraction, multiplication, and division. Here’s an example of how you can use them:
“`elixir
4+2
6
6*9
54
8/2
4.0
9-3
6
“`
Operator precedence is also supported, meaning that operators with higher precedence are evaluated first, followed by lower precedence. For example:
“`elixir
5+3*2
11
(5+3)*2
16
“`
These operators can also be used with variables, making it easy to write code that performs arithmetic operations. For example:
“`elixir
a = 5
b = 3
IO.puts a+b*2
“`
The output would be 11.
The arithmetic operator / always returns a float, regardless of the data type of the input. That means that if you divide an integer by another integer, it will still return a float. For example:
“`elixir
9/3
3.0
“`
Finally, the modulus operator ( % ) can be used to get the remainder of a division operation:
“`elixir
9%3
2
8%4
0
7%5
2
Tuples
Tuples are used to store multiple values in a single data structure. They can store any type of value, and the order of the elements is preserved. They’re like arrays in JavaScript
Tuples are declared using parentheses ( ) followed by comma-separated values:
“`elixir
tuple = {1, 2, 3}
tuple
{1, 2, 3}
“`
To retrieve the elements of a tuple, you can use the pattern-matching operator ( <- ). For example:
“`elixir
{a, b, c} <- {1, 2, 3}
a
1
b
2
c
3
“`
Keyword Lists
Elixir also provides a data structure called keyword lists. These are similar to tuples, but the elements are stored in name-value pairs, and they can be accessed by name using the brackets operator ( [] ).
Think of keyword lists as dictionaries in Python or objects in JavaScript.
Keyword lists are declared using a colon ( : ) followed by comma-separated name-value pairs:
“`elixir
list = [a: 1, b: 2, c: 3]
Functions and Modules
In Elixir, functions are defined using the def keyword.
Here’s an example of a simple function that takes two arguments and returns the sum:
“`elixir
def add(a, b) do
a + b
end
“`
The syntax for function calls is the same as in other languages. For example:
“`elixir
add(1, 2) #=> 3
“`
Elixir also allows you to define functions inside a module. Modules are used to organize related functions and provide namespacing. Here’s an example of a module with two functions:
“`elixir
defmodule Math do
def add(a, b) do
a + b
end
def subtract(a, b) do
a – b
end
end
“`
To call one of these functions, you would use the dot notation:
“`elixir
Math.add(1, 2) #=> 3
“`
The string module also provides a variety of functions for manipulating strings. For example:
“`elixir
String.capitalize(“hello world”) #=> “Hello World”
“`
String.length(“Elixir Rocks!”) #=> 13
“`
String.upcase(“elixir rocks!”) #=> “ELIXIR ROCKS!”
“`