Elixir
Elixir, created by José Valim in 2011, runs on the same virtual machine as Erlang and inherits its lightweight processes and fault tolerance. It adds a Ruby-like syntax, macros, a great build tool (Mix) and a strong ecosystem, including the Phoenix web framework.
Paradigm: Concurrent and Actor Programming
What Makes Elixir Special
- Actors on the BEAM. Processes are isolated and cheap, and communicate by messages. Elixir wraps this in behaviours such as
GenServer,SupervisorandTask. - Functional and immutable. Data cannot be changed. Pattern matching, the pipe operator
|>and recursion replace loops and mutation. - Supervision trees. You declare how to restart children when they crash, and the failure of one process does not take down the rest.
- Macros and metaprogramming. Much of the language is written with macros, so libraries can add new syntax safely.
- Built-in tooling. Mix, ExUnit, doctests and the
iexshell come with the language, and Livebook and Nx extend it to notebooks and machine learning.
Example: A counter as a GenServer
defmodule Counter do
use GenServer
# client API
def start_link(initial \\ 0), do: GenServer.start_link(__MODULE__, initial)
def increment(pid), do: GenServer.cast(pid, :increment)
def value(pid), do: GenServer.call(pid, :value)
# server callbacks
@impl true
def init(n), do: {:ok, n}
@impl true
def handle_cast(:increment, n), do: {:noreply, n + 1}
@impl true
def handle_call(:value, _from, n), do: {:reply, n, n}
end
{:ok, pid} = Counter.start_link()
Counter.increment(pid)
Counter.increment(pid)
Counter.value(pid) # => 2
How It Works
use GenServerbrings in the generic server behaviour: the loop, the mailbox and the message protocol are already written.- The client functions hide the messages.
castis asynchronous (fire and forget), andcallwaits for a reply. - Each callback receives the current state and returns the next one, such as
{:noreply, n + 1}. State changes without any variable being assigned. - The counter runs in its own process, and any number of callers can use it safely with no locks.
History and Where It Is Used
Elixir powers Phoenix web applications and real-time channels (Discord uses it at scale), IoT firmware through Nerves, and data pipelines with Broadway. See the Elixir roadmap for a complete course.