Elixir
Table of Contents
Dynamically typed functional language running on the Erlang VM (BEAM). Built for scalable, fault-tolerant, distributed systems. Core strengths: lightweight concurrency via the Actor Model, immutable data, pattern matching, and the "let it crash" fault-tolerance philosophy. Primary use case is web applications via the Phoenix Framework.
Related: Erlang Actor Model Concurrency Functional Programming Immutability Pattern Matching Metaprogramming
Core Features
Immutability
Data structures cannot be mutated in place — operations return new values. Eliminates shared mutable state bugs in concurrent code. See Immutability.
Pattern Matching
= matches and destructures simultaneously. Used in function
heads, case expressions, and with blocks.
# Basic match
{:ok, value} = {:ok, 42}
# value == 42
# Function clauses via pattern matching
defmodule Greeter do
def greet(:english), do: "Hello"
def greet(:dutch), do: "Hallo"
def greet(_), do: "Hi"
end
# Case expression
case response do
{:ok, result} -> "Success: #{result}"
{:error, reason} -> "Error: #{reason}"
end
Concurrency — Processes and the Actor Model
Elixir processes are lightweight (not OS threads) — hundreds of thousands can run concurrently. Processes communicate by message passing; they share no memory. See Actor Model.
# Spawn a process
pid = spawn(fn -> IO.puts("Hello from a process") end)
# Send a message
send(pid, {:greet, "Alice"})
# Receive a message
receive do
{:greet, name} -> IO.puts("Hello, #{name}")
_other -> IO.puts("Unknown message")
after
5000 -> IO.puts("Timeout")
end
Fault Tolerance — Supervisors
"Let it crash" — processes are expected to fail; supervisors restart them in a clean state. Fault isolation prevents one failed process from cascading.
defmodule MyApp.Application do
use Application
def start(_type, _args) do
children = [
MyApp.Worker, # supervised worker process
{MyApp.Server, port: 4000} # with arguments
]
opts = [strategy: :one_for_one, name: MyApp.Supervisor]
Supervisor.start_link(children, opts)
end
end
Strategies:
:one_for_one— restart only the failed child:one_for_all— restart all children if one fails:rest_for_one— restart failed child and all started after it
Pipe Operator
Chains function calls linearly — value flows left to right as the first argument of each function:
# Without pipe (nested)
String.downcase(String.trim(" Hello World "))
# With pipe (linear)
" Hello World "
|> String.trim()
|> String.downcase()
|> String.split(" ")
# => ["hello", "world"]
Macros
Compile-time metaprogramming — macros receive AST and return transformed AST. Used to build DSLs (Phoenix Router, Ecto queries).
defmacro unless(condition, do: body) do
quote do
if !unquote(condition), do: unquote(body)
end
end
Syntax Quick Reference
# Variables
name = "Alice"
# Atoms (symbols)
:ok
:error
# Tuples
{:ok, 42}
{:error, "not found"}
# Lists (linked)
[1, 2, 3]
[head | tail] = [1, 2, 3] # head = 1, tail = [2, 3]
# Maps
user = %{name: "Alice", age: 30}
user.name # => "Alice"
user[:name] # => "Alice"
%{user | age: 31} # update — returns new map
# Strings (UTF-8 binaries)
"Hello, #{name}" # interpolation
# Anonymous functions
double = fn x -> x * 2 end
double.(5) # => 10
# Named function shorthand
double = &(&1 * 2)
double.(5) # => 10
# Modules and functions
defmodule Math do
def square(x), do: x * x
defp private_fn, do: :secret # defp = private
end
# Conditionals
if condition, do: a, else: b
unless condition, do: a
cond do
x > 10 -> "big"
x > 5 -> "medium"
true -> "small"
end
Mix — Build Tool
# Create a new project mix new my_app mix new my_app --sup # with supervisor (recommended) # Install dependencies mix deps.get # Compile mix compile # Run tests mix test mix test test/my_test.exs # specific file # Interactive shell with project loaded iex -S mix # Run the application mix run --no-halt # Format code mix format # Hex package manager mix hex.search phoenix
Tips
- Pattern matching is the primary control flow mechanism — reach for it before reaching for if/else
- Prefer
withfor chaining multiple pattern matches that can fail - Processes are cheap — spawn one per task rather than sharing state
- The pipe operator changes how you think about function composition — write small, focused functions that chain naturally
- Elixir's error handling convention: return
{:ok, value}or{:error, reason}tuples rather than raising exceptions for expected failure cases