Elixir Cheat Sheet

Quick reference for Elixir — basics, pattern matching, collections, functions, modules, processes, OTP, pipe operator, and control flow. All essential patterns in one page.

Basics Pattern Matching Collections Functions & Modules Processes & OTP Pipe Operator Control Flow

Basics

x = 42 Variable binding (rebindable)
"Hello #{name}" String interpolation
:ok / :error Atoms — named constants
{:ok, value} Tuple — fixed-size container
[1, 2, 3] List — linked list
%{name: "Alice", age: 30} Map — key-value store
<<72, 101, 108>> / <<"hello">> Binary / bitstring
1..10 Range
# single line comment Comment syntax
is_integer(x) / is_binary(s) / is_atom(a) Type checking guards

Pattern Matching

{:ok, result} = {:ok, 42} Match tuple — result is 42
[head | tail] = [1, 2, 3] Match head and tail of list
%{name: name} = %{name: "Alice", age: 30} Match map — extract name
{_, second, _} = {1, 2, 3} Underscore ignores values
^x = value Pin operator — match against existing value
<> = "hello" Binary pattern matching
def greet(%User{name: name}), do: "Hi #{name}" Match struct in function args
case result do {:ok, v} -> v; {:error, e} -> raise e end Pattern match with case

Collections

Enum.map([1,2,3], &(&1 * 2)) Map over list → [2, 4, 6]
Enum.filter(list, &(&1 > 2)) Filter elements
Enum.reduce(list, 0, &(&1 + &2)) Reduce / fold list
Enum.find(list, &(&1 == 3)) Find first matching element
Enum.sort_by(users, & &1.name) Sort by field
Enum.chunk_every(list, 3) Split into chunks of 3
Enum.zip(list_a, list_b) Zip two lists into tuple pairs
Map.put(map, :key, "value") Add/update key in map
Map.merge(map1, map2) Merge two maps
Keyword.get(opts, :timeout, 5000) Get from keyword list with default

Functions & Modules

def add(a, b), do: a + b Named public function
defp helper(x), do: x * 2 Private function
fn x, y -> x + y end Anonymous function
&(&1 + &2) Capture syntax — short anonymous function
def greet(name \\ "World"), do: "Hello #{name}" Default argument
def area(:circle, r), do: 3.14 * r * r Multi-clause function with pattern match
def fetch(x) when is_integer(x) and x > 0 Guard clause
defmodule MyApp.User do ... end Module definition
use GenServer / import Enum / alias MyApp.Repo use / import / alias
@moduledoc "User module" / @doc "Creates a user" Module and function docs

Processes & OTP

spawn(fn -> IO.puts("hello") end) Spawn a new process
send(pid, {:msg, "hi"}) Send message to process
receive do {:msg, text} -> text after 5000 -> :timeout end Receive with timeout
Task.async(fn -> expensive_work() end) Async task
Task.await(task, 10_000) Await task result with timeout
GenServer.start_link(MyServer, initial_state) Start GenServer
def handle_call(:get, _from, state), do: {:reply, state, state} Synchronous GenServer callback
def handle_cast({:put, val}, _state), do: {:noreply, val} Asynchronous GenServer callback
use GenServer / @impl true GenServer boilerplate
Supervisor.start_link(children, strategy: :one_for_one) Start supervisor with restart strategy

Pipe Operator

"hello" |> String.upcase() |> String.reverse() Chain transformations with pipe
list |> Enum.filter(&(&1 > 0)) |> Enum.sum() Filter then sum with pipe
conn |> put_status(200) |> json(%{ok: true}) Phoenix controller pipe chain
data |> Jason.encode!() |> Base.encode64() Encode JSON then Base64
params |> Map.take([:name, :email]) |> Map.put(:role, :user) Transform map with pipes
"path/to/file" |> File.read!() |> String.split("\n") Read file and split lines
1..100 |> Stream.filter(&(rem(&1,2)==0)) |> Enum.take(5) Lazy stream with pipe

Control Flow

if condition, do: "yes", else: "no" If/else expression
unless condition, do: "nope" Unless (negated if)
case value do :ok -> "good"; :error -> "bad" end Case expression with pattern match
cond do x > 10 -> "big"; x > 0 -> "small"; true -> "zero" end Cond — multiple conditions
with {:ok, a} <- fetch_a(), {:ok, b} <- fetch_b(a), do: {:ok, a + b} With — chain pattern matches (happy path)
try do ... rescue e in RuntimeError -> ... after ... end Try/rescue/after
raise "Something went wrong" Raise runtime error
throw(:abort) / catch :abort Throw and catch (rare, non-local return)
Step-by-Step Guide

How to Test an API Online

Read Guide →

More Cheat Sheets