Skip to content
LumenaryAcademy
Foundations 50 min

Values, types and pattern matching

Elixir's basic types, why its data never changes, and the match operator that takes data apart.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Values that never change

In most languages you learned first, a variable is a box. You put a list in the box, then call a method that changes the list in place, and anyone else holding the same box sees the change. That is convenient right up to the moment two parts of a program, or two threads, change the same thing at the same time.

Elixir takes the boxes away. Every value is immutable: once a list, a map or a string exists, nothing can change it. Functions that look as if they modify data, such as adding an item to a list or updating a key in a map, return a new value and leave the old one alone. This is not as wasteful as it sounds, because the new value shares most of its structure with the old one; adding to the front of a list of a million items creates one new cell, not a copy of a million.

Immutability is what makes the BEAM's processes safe. When one process sends data to another, neither can change it behind the other's back, so there is nothing to lock. It also makes code easier to reason about: if you hand a map to a function, you know your map will look the same when the function returns.

The second big idea of this lesson follows from the first. If values never change, the = sign does not need to mean "put this in a box". In Elixir it means match: "make the left side look like the right side". That small change turns out to be one of the most useful features of the language. You will use it to take apart tuples, lists, maps and strings, to choose what to do based on the shape of data, and, in the next lesson, to write functions as a set of cases.

DefinitionsH

The basic types

Here are the types you will use every day, with a literal for each:

TypeExamplesNotes
integer42, -7, 1_000_000, 0xFFarbitrary precision: never overflows
float3.14, 1.0e-964-bit IEEE 754 double
atom:ok, :error, true, nila constant whose value is its name
string"héllo"UTF-8 text, stored as a binary
charlist~c"hello"a list of code points, mostly for Erlang libraries
list[1, 2, 3]linked list; can mix types
tuple{:ok, 42}fixed size, stored contiguously
map%{"name" => "Ana", age: 31}key-value store; any type as key
keyword list[timeout: 5000, retries: 3]a list of {atom, value} tuples, used for options
range1..10, 1..10//3a sequence of integers, with an optional step

Functions, process identifiers (PIDs), references and ports are values too; you will meet them later.

Atoms deserve a closer look. :ok is an atom, and so are true, false and nil (written without the colon for convenience). Module names are atoms as well: String is shorthand for :"Elixir.String", and Erlang modules are plain atoms such as :math. Atoms are compared by identity, which makes them fast and ideal as tags. One caution: atoms are not garbage-collected and the BEAM has a limit on how many can exist (about a million by default), so never turn unbounded user input into atoms.

Some operators surprise people coming from other languages. / always returns a float; use div and rem for integer division. == compares numbers by value (1 == 1.0 is true), while === also requires the same type. The boolean operators and, or and not require actual booleans, while &&, || and ! accept any value and treat only false and nil as false, so nil || "default" is a common way to supply a fallback.

elixir
IO.inspect(10 / 2)
IO.inspect(div(7, 2))
IO.inspect(rem(7, 2))
IO.inspect(2 ** 100)
IO.inspect(0.1 + 0.2)

IO.inspect(1 == 1.0)
IO.inspect(1 === 1.0)
IO.inspect(nil || "default")
IO.inspect(is_atom(:ok) and is_atom(true) and is_atom(String))

IO.inspect(%{"city" => "Lagos", population: 15_000_000})
IO.inspect(Enum.to_list(1..10//3))

It prints:

text
5.0
3
1
1267650600228229401496703205376
0.30000000000000004
true
false
"default"
true
%{:population => 15000000, "city" => "Lagos"}
[1, 4, 7, 10]

Two details in that output are worth a second look. 0.1 + 0.2 is not exactly 0.3, as in every language that uses binary floating point; for money, use integers (cents) or a decimal library. And the map printed its keys in a different order from the one we wrote, and switched to the => syntax for every key because it mixes atom and string keys. Maps have no promised order; never rely on it.

The map literal shows two syntaxes: "city" => "Lagos" works for keys of any type, and population: 15_000_000 is shorthand for :population => 15_000_000 when the key is an atom. The shorthand must come last.

Worked examplesH

Strings, binaries and charlists

A string in Elixir is a binary, a sequence of bytes, that holds valid UTF-8. That design means strings are compact and fast to send between processes, but it also means you must decide whether you care about bytes or about characters. The String module works with graphemes, the characters a reader perceives, even when one of them is built from several Unicode code points:

elixir
word = "Zürich"
IO.puts(String.length(word))
IO.puts(byte_size(word))
IO.puts(String.upcase(word))
IO.puts(String.reverse("añil"))

coder = "👩‍💻"
IO.puts("graphemes: #{String.length(coder)}, code points: #{length(String.codepoints(coder))}, bytes: #{byte_size(coder)}")

IO.inspect(String.split("red,green,,blue", ","))
IO.inspect(String.split("  spaced   out  "))
IO.puts("Elixir" <> " " <> "1.20")
IO.inspect(~c"BEAM")
IO.inspect(<<72, 105>>)

It prints:

text
6
7
ZÜRICH
liña
graphemes: 1, code points: 3, bytes: 11
["red", "green", "", "blue"]
["spaced", "out"]
Elixir 1.20
~c"BEAM"
"Hi"

The woman-technologist emoji is one grapheme, built from three code points (woman, an invisible joiner, and laptop) and eleven bytes. String.reverse and String.length respect graphemes, which is why "añil" reversed correctly. String.split/1 with no separator splits on runs of whitespace and drops empty pieces, while String.split/2 keeps empty strings between consecutive separators. Finally, <<72, 105>> is binary syntax: two bytes that happen to be valid UTF-8, so IO.inspect shows them as the string "Hi".

Charlists are a leftover from Erlang, where text was traditionally a list of integer code points. You need them only when calling certain Erlang functions; write them with the ~c sigil. Older code writes them in single quotes, 'hello', and Elixir 1.20 prints a deprecation warning for that spelling and suggests mix format --migrate to rewrite it. If you ever see ~c"..." printed where you expected a list of numbers, that is why: IO.inspect([104, 105]) prints ~c"hi" because every number in the list is a printable code point.

DefinitionsH

The match operator

Definition— Pattern match

The expression pattern = value succeeds when the value has the shape the pattern describes. Every unbound variable in the pattern is bound to the corresponding part of the value, and the whole expression returns the value. If the value does not fit, the match raises a MatchError.

With a plain variable on the left, a match always succeeds and binds the variable, so x = 5 looks like assignment. The difference shows when the left side has structure:

elixir
{status, count} = {:ok, 3}
IO.puts("status=#{status} count=#{count}")

[first, second | rest] = ["Accra", "Hanoi", "Lima", "Oslo"]
IO.puts("first=#{first} second=#{second}")
IO.inspect(rest, label: "rest")

%{name: name} = %{name: "Ifeoma", role: :admin, active: true}
IO.puts("name=#{name}")

"Bearer " <> token = "Bearer abc123"
IO.puts("token=#{token}")

{_, _, year} = {28, 11, 2026}
IO.puts("year=#{year}")

result =
  try do
    {:ok, value} = {:error, :timeout}
    value
  rescue
    error in MatchError -> "no match: #{inspect(error.term)}"
  end

IO.puts(result)

It prints:

text
status=ok count=3
first=Accra second=Hanoi
rest: ["Lima", "Oslo"]
name=Ifeoma
token=abc123
year=2026
no match: {:error, :timeout}

Line by line:

  • A tuple pattern must have the same size as the tuple, and each position is matched in turn.
  • [head | tail] is the fundamental list pattern: it splits a non-empty list into its first element and the rest. [a, b | rest] takes two from the front. Lists in Elixir are linked lists, and this pattern is how almost all list processing starts.
  • A map pattern matches if the listed keys are present, ignoring any others. That makes map patterns robust: adding a field to a map does not break code that matches on the fields it needs.
  • "Bearer " <> token matches a string that starts with a known prefix and binds the rest. (Only a literal prefix is allowed on the left of <> in a pattern.)
  • _ matches anything and binds nothing. Variables starting with an underscore, such as _day, do the same but document what is being ignored.
  • When the shapes disagree, the match raises. The try/rescue here only exists to show the error; you will learn when (rarely) to rescue in Control flow, errors and testing.
Worked examplesH

Rebinding and the pin operator

Because values are immutable, you might expect variables to be unchangeable too. They are not quite: you can rebind a name to a new value. x = 1 followed by x = x + 1 is legal, and afterwards x names the value 2. Nothing was mutated; the name simply points at a different value from then on. Code that captured the old value (a function defined earlier, a message already sent) still sees 1.

Rebinding creates a puzzle for matching. In {x, :ok} = something, does x mean "bind a new x" or "the value x already has"? Elixir chooses "bind a new one". When you want to match against the current value, you pin the variable with ^:

elixir
expected = "Zanele"

case {"Zanele", 92} do
  {^expected, score} -> IO.puts("#{expected} scored #{score}")
  {other, _} -> IO.puts("unexpected student #{other}")
end

case {"Thabo", 77} do
  {^expected, score} -> IO.puts("#{expected} scored #{score}")
  {other, _} -> IO.puts("unexpected student #{other}")
end

results = [{:ok, 12}, {:error, :not_found}, {:ok, 30}, {:error, :timeout}]

for result <- results do
  case result do
    {:ok, n} when n > 20 -> IO.puts("big success: #{n}")
    {:ok, n} -> IO.puts("success: #{n}")
    {:error, :timeout} -> IO.puts("timed out, will retry")
    {:error, reason} -> IO.puts("failed: #{reason}")
  end
end

It prints:

text
Zanele scored 92
unexpected student Thabo
success: 12
failed: not_found
big success: 30
timed out, will retry

The second half introduces case, which you will use constantly. It tries each pattern from top to bottom and runs the body of the first one that matches. A clause can add a guard with when, a condition that must also hold; {:ok, n} when n > 20 matches only big successes. Order matters: the specific {:error, :timeout} clause comes before the general {:error, reason}, or it would never be reached. If no clause matches, case raises a CaseClauseError, which is usually what you want: an unexpected value is a bug, and failing loudly is better than carrying on with nonsense.

Notice also the shape of results. Tagged tuples, {:ok, value} for success and {:error, reason} for failure, are the most common convention in Elixir. Functions in the standard library return them, case and pattern matching take them apart, and you will meet them in nearly every lesson from here on.

IntuitionH

Sharing, not copying

If every change produces a new value, why doesn't an Elixir program spend all its time copying? Because immutable values can be shared safely. Consider:

elixir
old = [2, 3]
new = [1 | old]
123newoldone new cellshared with old, unchanged
Prepending to a list allocates one new cell whose tail is the existing list. Both names are valid at once, and nothing was copied.

The new list is one cell holding 1 whose tail is the old list. Nobody can modify [2, 3], so it does not matter that two names lead to it. The same idea scales to maps: Map.put/3 on a large map builds a few new internal nodes along the path to the changed key and shares everything else. Tuples are the exception that proves the rule: they are flat blocks of memory, so changing one element copies the tuple, which is why tuples are kept small.

There is one place where the BEAM does copy deliberately: when a message goes from one process to another, its data is copied into the receiving process's heap (large binaries, over 64 bytes, are the exception: they live in a shared area and are passed by reference). Copying sounds expensive, but it buys something precious. Each process owns all of its memory, so each can be garbage-collected on its own, in microseconds, without stopping the rest of the system. That is a large part of why Elixir services keep their response times steady under load.

Common misconceptionsH

Common mistakes

Misconception

"= assigns, so 5 = x is nonsense." It is a perfectly good match: if x is bound to 5, it succeeds; otherwise it raises MatchError. Reading = as "must match" rather than "becomes" is the single most useful habit for this language.

Misconception

"Rebinding means Elixir has mutable variables after all." Rebinding gives a name a new value; it never changes a value. A list you passed to another function, or sent to another process, is exactly as it was. The difference matters in closures: an anonymous function that captured x before you rebound it keeps the old value.

Misconception

"String.length is cheap, like len in other languages." It walks the whole string to count graphemes, so it is linear in the string's size. When you need the size in bytes (for a buffer, a protocol or a database limit), byte_size is constant time. The same is true of lists: length(list) walks the list, so avoid calling it in a loop.

Misconception

"A map pattern must list every key." It need not, and should not. %{name: name} matches any map with a :name key. The exception is the empty map pattern %{}, which matches every map; to test for an empty map, compare with map_size(m) == 0 or m == %{}.

Exercises

Exercises

1. Values, types and pattern matching

Warm-upComputational

What does IO.inspect(7 / 2) print?

2. Values, types and pattern matching

Warm-upComputational

After [a, b | rest] = [10, 20, 30, 40, 50], what is length(rest)?

3. Values, types and pattern matching

CoreComputational

Which of these matches raises a MatchError?

Choose one

4. Values, types and pattern matching

CoreComputational

What does this program print?

limit = 10
value = 10

case value do
  ^limit -> IO.puts("at limit")
  n when n > limit -> IO.puts("over")
  _ -> IO.puts("under")
end

5. Values, types and pattern matching

CoreComputational

Which of these patterns match the value %{id: 7, tags: ["a"]}? List their letters.

  • A: %{id: _}
  • B: %{}
  • C: %{id: 7, name: _}
  • D: %{tags: [_]}
  • E: %{tags: []}

Write elements separated by commas. Order and repeats don’t matter — just like in a set!

6. Values, types and pattern matching

StretchComputational

What does this program print?

x = 1
f = fn -> x end
x = 2
IO.puts(f.() + x)

7. Values, types and pattern matching

Warm-upComputational

What is div(17, 5) + rem(17, 5)?

Further reading and resources