Elixir Cheatsheet

Pattern Matching

Use this Elixir reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Match Operator

= matches the pattern on the left against the value on the right.

name = "Ada"
{name, age} = {"Ada", 36}
[head | tail] = [1, 2, 3]
%{role: role} = %{name: "Ada", role: "admin"}

If the shapes are incompatible, Elixir raises MatchError.

Pin Operator

Variables normally rebind in a match. Use ^ to require the current value.

x = 10
{x, y} = {20, 30}   # x is rebound to 20
^x = 20             # ok
^x = 21             # MatchError

Ignoring Values

{:ok, value} = {:ok, 42}
{:ok, _value} = {:ok, 42}
{_, second, _} = {:a, :b, :c}

Use _ or a name beginning with _ for values you intentionally ignore.

case

case Integer.parse(text) do
  {n, ""} -> {:ok, n}
  {_n, rest} -> {:error, {:trailing_text, rest}}
  :error -> {:error, :not_a_number}
end

case tries patterns top to bottom. Guards can refine a pattern.

cond

cond do
  score >= 90 -> "A"
  score >= 80 -> "B"
  score >= 70 -> "C"
  true -> "keep practicing"
end

Use cond for ordered boolean checks. The final true is the else branch.

with

with {n, ""} <- Integer.parse(text),
     true <- n > 0 do
  {:ok, n}
else
  _ -> {:error, :invalid_positive_integer}
end

with chains matches. The first failed match jumps to else.

Guards

Common guard-safe helpers include is_integer/1, is_binary/1, is_list/1, is_map/1, is_atom/1, is_nil/1, length/1, comparisons, and, or, and not.

def label(n) when is_integer(n) and n > 0, do: :positive
def label(0), do: :zero
def label(_), do: :other