Elixir basics: what the language is and where it is used
What Elixir is
Elixir is a functional language for systems
that must keep serving while parts of them fail. It runs on the
Erlang virtual machine, so a program gets
lightweight processes, message passing and supervisors that restart
what crashed without writing any of that itself.
The syntax is modern and the data is immutable: a function takes
values in and returns new values out, and nothing changes in place.
The tooling is part of the language rather than an add-on: Mix builds
projects, Hex fetches dependencies and ExUnit runs the tests.
Install Elixir and check the version
The Elixir package pulls in the Erlang runtime, so two commands are enough on Ubuntu and the other Linux systems with APT:
sudo apt update
sudo apt install elixir
Both halves report their version, the Erlang runtime first and Elixir second:
elixir --version
Erlang/OTP 27 [erts-15.2] [64-bit]
Elixir 1.18.2 (compiled with Erlang/OTP 27)
The runtime can be asked directly for its release number, which is the number that names the OTP documentation:
elixir -e "IO.puts(:erlang.system_info(:otp_release))"
27
The interactive shell
iex runs every line the moment you press Enter, so an idea can be tested before it goes into a file:
iex
Interactive Elixir - press Ctrl+C to exit (type h() ENTER for help)
iex> 1 + 2
3
iex> "hi " <> "there"
"hi there"
The shell is also the manual: h(Enum.map) prints the documentation of one function, and Tab completes a name. Leave it with Ctrl+C twice or with System.halt().
Your first script
A script is a plain text file with the exs extension. Save this as hello.exs:
IO.puts("Hello, Elixir")
Run it by passing the file name, with its extension, to the elixir command:
elixir hello.exs
Hello, Elixir
Strings join with <>, and #{} drops a value straight into a string. Data flows through a chain of calls with the pipe operator, which feeds the result on the left into the first argument on the right:
name = "Ada"
IO.puts("Hello, " <> name) # Hello, Ada
" hello " |> String.trim() |> String.upcase() # "HELLO"
The versions and the output on this page come from the elixir package of Ubuntu, which carried Elixir 1.18.2 on Erlang/OTP 27 (x86_64). A newer release prints its own numbers.
The course
The
Elixir course
goes on for fifty lessons: the language core, then modules, structs
and protocols, then OTP with GenServer and supervisors, Mix projects,
ExUnit tests and two capstone projects.
Start with lesson 1,
What is Elixir and where it runs,
and follow the chain of previous and next links at the bottom of every
page.
Article author: Arthur Isaev