Chapter 2 — Syntax Translation Guide
For Erlang developers the biggest perceived barrier is syntax. Reality: the concepts are identical; only keywords and surface forms differ. This chapter is your translation dictionary — read it once, then keep it as a reference.
How to use it: each section pairs a concept table with side-by-side code. The tables are for lookup; the code is for building intuition.
2.1 Code Organization
| Concept | Erlang | Elixir |
|---|---|---|
| File extension | .erl | .ex / .exs |
| Module declaration | -module(name). | defmodule Name do ... end |
| Export functions | -export([fun/arity]). | def fun(args) (public by default) |
| Private functions | Not exported | defp fun(args) |
| Include files | -include("file.hrl"). | Not needed (import/alias) |
| Module attributes | -define(MACRO, value). | @attribute value |
| Comments | % comment | # comment |
Erlang — annotated:
-module(math). % module name = file name = atom
-export([add/2, sub/2]). % opt-in exports; nothing public by default
-define(DEFAULT, 0). % compile-time macro constant
add(A, B) -> A + B.
sub(A, B) -> A - B.
Elixir — same program:
defmodule Math do # CamelCase alias; compiles to atom :"Elixir.Math"
@default 0 # module attribute — inlined at compile time
def default, do: @default
def add(a, b), do: a + b # def = exported (public) by default
def sub(a, b), do: a - b
defp private_fun, do: :ok # defp = private, invisible outside this module
end
Two mental flips worth noting:
- Visibility inverts. Erlang is private-by-default (
-exportopts in); Elixir is public-by-default (defpopts out). Idiomatic Elixir still keeps most functionsdefp— treat public surface as deliberate API design. - Module names are aliases.
MyApp.Utilsis sugar for the atom:"Elixir.MyApp.Utils"; nested naming is convention plus aliasing, covered in §2.2. There are no dotted atoms likemy_app_utils.
.ex vs .exs: .ex compiles to BEAM files on disk (your application);
.exs is script form — evaluated directly, nothing written to disk
(tests, config, Mix files). Like .erl vs running erl -s ... one-offs,
but first-class in tooling.
Attributes vs Macros: What Happens at Compile Time
@attribute succeeds -define, but the mechanics differ in one useful way:
a -define performs textual substitution wherever invoked; an attribute
stores a value (an Elixir term, or quoted code) evaluated once, then
inlined at each reference:
defmodule Config do
@ttl 60 # a plain value — inlined at every use
@routes [:health, :metrics] # lists, maps — any term works
def ttl, do: @ttl # compiles down to the literal 60
def fresh?(now, seen) when now - seen <= @ttl, do: :fresh
def fresh?(_, _), do: :stale # attributes are legal IN GUARDS — by the
end # time guards elaborate, @ttl IS 60
Two power tools ride the same mechanism: accumulate: true collects
repeated attributes into a list, and persist: true writes an attribute into
the .beam metadata — the chunk mechanism that also carries Erlang’s
compile-time attributes.
Be precise about who uses which. accumulate: true is what lets a module
declare @behaviour once and have every clause-defined function contribute
to a single list; the canonical Elixir examples are @before_compile,
@after_compile, and custom DSL registries — Ch 06 §6.4 builds one.
@moduledoc and @doc are a separate mechanism: each clause carries its
own @doc, and both land in the documentation chunk that Chapter 03’s ExDoc
flow consumes. Do not model docs as an accumulating attribute.
2.2 Modules, Imports, Constants
| Concept | Erlang | Elixir |
|---|---|---|
| Define module | -module(name). | defmodule Name do ... end |
| Alias long name | Manual | alias MyApp.LongModule, as: Short |
| Import functions | Not built-in | import Module, only: [fun: arity] |
| Require macros | -include_lib(...) | require Module |
| Compile-time constant | -define(PI, 3.14). | @pi 3.14 |
Four distinct tools replace Erlang’s single include mechanism:
- alias — rename a module for qualified calls:
alias MyApp.Long.Modulelets you writeModule.run/1. Zero runtime effect; pure naming. - import — bring functions into local scope so they’re called unqualified.
Restrict with
only:/except:to keep provenance readable. - require — makes a module’s macros available (macros must be required before use — the compiler needs to expand them).
- @attribute — compile-time constants and annotations, the
-definesuccessor (plus metadata roles like@doc,@spec,@impl).
Side-by-side retry utility:
defmodule MyApp.Utils do
@max_retries 3 # inlined wherever referenced — same
# expansion semantics as -define
def retry(_fun, 0), do: {:error, :max_retries} # clause 1: base case
# (pattern on arg count!)
def retry(fun, n) do # clause 2: recursive case
case fun.() do # note: anonymous fns call
:ok -> :ok # with .()
_ -> retry(fun, n - 1)
end
end
end
The Erlang twin you’d write (retry(F, N) -> case F() of ... end,
clauses and all) has an identical recursion shape: pattern-matching-on-
clauses, first clause the base case. Differences are punctuation: no
terminating dot, clauses separated implicitly by newline, fun.() instead of
(Fun)().
From Erlang you know: module attributes compile to the same constants mechanism as
-define.@max_retries 3is inlined at expansion time.
2.3 Records → Structs
Structs are maps with a compile-time-checked __struct__ field. They replace
records with better pattern matching, enforced keys, and protocol dispatch
(Ch 05):
| Concept | Erlang (Records) | Elixir (Structs) |
|---|---|---|
| Definition | -record(user, {name, age}). | defstruct [:name, :age] inside a module |
| Creation | #user{name = "Alice"} | %User{name: "Alice"} |
| Access | User#user.name | user.name |
| Update | User#user{age = 31} | %{user | age: 31} |
| Pattern match | #user{name = Name} = R | %User{name: name} = user |
| Defaults | -record(user, {name = "", age = 0}) | defstruct name: "", age: 0 |
| Required keys | No | Yes (@enforce_keys) |
defmodule User do
@enforce_keys [:id] # compile error if :id missing at construction
defstruct [:id, name: "", age: 0]
end
# Multi-clause accessors read exactly like record guards:
def get_name(%User{name: name}), do: name
def update_age(%User{} = user, new_age) do
%{user | age: new_age} # update syntax: raises if key doesn't exist
end
Three upgrades over records to appreciate:
- One struct per module — the module becomes home to related functions (constructors, domain logic), not just data.
@enforce_keysturns “forgot to set the field” into a compile-time crash instead of a runtimeundefined.- Structs participate in protocols (§5.2) and get pretty inspection for free.
Structs Under the Hood: Just a Tagged Map
A struct is literally a map carrying a __struct__ key — no new VM type,
which is why records-as-tuples never needed special VM support either:
iex> user = %User{id: 1, name: "Ada"}
iex> user.__struct__
User
iex> is_map(user) && is_struct(user)
true
iex> %{name: name} = user # a plain-map pattern MATCHES a struct…
"Ada"
That last line is the standing footgun: %{} matches any struct, so a
loose map pattern silently accepts foreign types. Match %User{} (pins the
type, not just fields) or guard with is_struct/2 when the type matters.
Conversely, Map and Access functions treat structs as plain maps —
handy for bulk work, risky when invariants matter (see §5.4).
2.4 Control Flow & Functions
Anonymous functions use fn instead of fun; clauses separate with newlines
instead of ;; no terminating dot. Everything below is iex-runnable:
# Anonymous function with multiple clauses — matches like any function head:
fun = fn
{:ok, value} -> value
{:error, reason} -> raise reason
end
fun.({:ok, 42}) #=> 42 # NOTE the .() call syntax for anonymous fns
# case — like Erlang's but semicolon-free; each arrow-clause on its own line
case File.read("config.txt") do
{:ok, body} -> body
{:error, :enoent} -> "default"
end
# try/catch/after — note the extra rescue arm for exceptions (Elixir adds
# structured exceptions ON TOP of Erlang's throw/exit/error classes):
try do
raise "oops"
rescue
e in RuntimeError -> "handled: #{e.message}" # exceptions → rescue
catch
:exit, reason -> handle_exit(reason) # exits → catch (as in Erlang)
after
:cleanup # always runs
end
Error Classes: throw, exit, raise Map Cleanly
Elixir keeps all three Erlang error classes and adds a friendlier front
door for the error class. Full mapping:
| Erlang construct | Class | Elixir home |
|---|---|---|
throw(Term) | :throw | throw(term) + catch arm |
exit(Reason) | :exit | exit(reason) + catch :exit, r -> |
erlang:error(R), badmatch, … | :error | raise + rescue arm |
rescue is sugar over catch :error that unwraps exception structs; the
plain catch clause still speaks raw classes, so interop code translates
verbatim:
try do
throw(:thrown_value)
catch
thrown -> {:caught_throw, thrown} # :throw class: single payload
end
#=> {:caught_throw, :thrown_value}
try do
exit(:shutdown_requested)
catch
:exit, reason -> {:caught_exit, reason}
end
#=> {:caught_exit, :shutdown_requested}
try do
raise ArgumentError, message: "bad input"
rescue
e in ArgumentError -> {:caught_error, e.message}
end
#=> {:caught_error, "bad input"}
Style rule: raise/rescue for your own APIs (structured, pattern-
matchable); reserve throw for non-local early returns inside library
macros (Plug uses it internally); exit stays what it always was — a
process-shutdown signal.
if is a macro built on case, with an optional else block.
Kernel.unless/2 was soft-deprecated in 1.18 — it still compiles with no
warning, and mix format --migrate rewrites it to if not ... — but the style
guide discourages it: unless reads as “if not”, and unless ... else is
actively confusing because the else branch is the “positive” case. Prefer
if not ... or an explicit case.
with: Chain Fallible Steps Without Nesting
The idiomatic answer to Erlang’s most common nesting pattern — a staircase
of cases threading {:ok, _} through several steps:
%% Erlang: each step nests one level deeper
load(Path) ->
case file:read_file(Path) of
{ok, Body} ->
case string:to_integer(string:trim(Body)) of
{Int, []} when Int > 0 -> {ok, Int};
_ -> {error, not_an_integer}
end;
{error, Reason} -> {error, Reason}
end.
defmodule ConfigLoader do
# each <- step runs, then pattern-matches its result;
# ANY mismatch drops straight to the else block
def load(path) do
with {:ok, body} <- File.read(path),
{int, ""} <- Integer.parse(String.trim(body)),
true <- int > 0 do
{:ok, int}
else
:error -> {:error, :not_an_integer} # Integer.parse miss
false -> {:error, :must_be_positive}
{:error, reason} -> {:error, reason} # File.read failure
end
end
end
iex> ConfigLoader.load("missing.txt")
{:error, :enoent}
iex> ConfigLoader.load("/tmp/ttl.txt") # containing "-5\n"
{:error, :must_be_positive}
Reading rules worth internalizing:
pattern <- exprrunsexprand matches the result againstpattern. A match binds and continues; a mismatch short-circuits intoelsecarrying the unmatched value (not an error).- Plain
exprlines (no<-) execute for effect or assert via=— a failed assert raisesMatchError, which is correct for programmer errors. - Without an
elseblock, a falling-through value is returned as-is — convenient when every step already speaks{:error, _}. elsearms are ordinarycaseclauses: order matters, guard them freely, and a final catch-all arm keeps unexpected failures visible instead of silently re-wrapped.
When to reach for which: one fallible call → case. Two or more steps
whose failures share handling → with. And resist the urge to route
control flow through with when there is nothing fallible — plain function
composition still reads best.
Capture Syntax — Read It Before You Need It
You will meet & everywhere in Elixir. Two forms, one idea — reference a
function without calling it:
&(&1 + 1) # anonymous capture: fn x -> x + 1 end
# &1, &2… are positional args
&is_atom/1 # named capture: the existing function is_atom/1
# module-qualified, arity explicit
Enum.filter([1, :a, 2, :b], &is_atom/1) #=> [:a, :b]
Enum.map([1, 2], &(&1 * 10)) #=> [10, 20]
This replaces Erlang’s fun X -> X * 10 end and fun lists:max/1-style
references. When you see &Mod.fun/arity in a pipe chain, mentally read
“pass that function itself along.”
One restriction: & captures functions only, never macros. Integer.is_even/1
is a defguard macro, so &Integer.is_even/1 compiles but raises
function Integer.is_even/1 is undefined or private the moment it is invoked
(shadowing the guard with a same-named function) — and calling it unqualified
needs require Integer first. Use an anonymous capture or a named fn when
the predicate is a guard:
Enum.filter(1..6, &(rem(&1, 2) == 0)) #=> [2, 4, 6]
require Integer
Enum.filter(1..6, fn n -> Integer.is_even(n) end) #=> [2, 4, 6]
Captured Functions with Bound Args
Documentation and discussions often say “a captured function with bound args.” The idea: take a function, pre-fill some arguments, and hand back a function needing only the rest. Four related but distinct concepts hide behind that phrase — learn to tell them apart:
| Concept | Example | What’s captured/bound? |
|---|---|---|
| Function capture | &String.upcase/1 | The function itself, no args |
| Closure | fn x -> x + n end | Variable n from outer scope |
| Partial application | fn x -> add.(10, x) end | Argument 10 |
| Capture with placeholder | &(&1 + 10) | 10 fixed; &1 still variable |
1. Plain capture — the function itself, nothing bound. &String.upcase/1
references the existing function without calling it:
iex> fun = &String.upcase/1
iex> fun.("hello")
"HELLO"
2. Closure — variables from the enclosing scope are baked in. Like an
Erlang fun, an Elixir fn captures surrounding bindings, and since
nothing rebinds, the capture is a frozen snapshot:
prefix = "Hello"
greet = fn name -> "#{prefix}, #{name}!" end # prefix is bound in HERE
greet.("Manh") #=> "Hello, Manh!"
threshold = 10
over? = fn x -> x > threshold end # threshold is baked in HERE
threshold = 999 # rebinds the outer name only
over?.(50) #=> true — still comparing against 10!
# (a live binding would give false)
The Erlang equivalents (Greet = fun(Name) -> ... end closing over
Prefix, Over = fun(X) -> X > Threshold end) behave identically, so this
is confirmation rather than news — but it explains why “stale closure” bugs
from mutable languages simply cannot happen here.
3. Partial application — bind arguments, not just variables. Fix the leading argument(s) of a function and keep the tail open:
add = fn a, b -> a + b end
add_10 = fn b -> add.(10, b) end # 10 is bound; b remains free
add_10.(5) #=> 15
The capture operator makes this one line — bound args written literally,
&1 standing for the argument still to come:
add = &Kernel.+/2
add_10 = &add.(10, &1) # read: "call add with 10 and my arg"
add_10.(5) #=> 15
You will meet this constantly with Enum callbacks — the surrounding value
rides along inside the function value:
factor = 10
Enum.map([1, 2, 3], fn x -> x * factor end) #=> [10, 20, 30]
# equivalently, with the factor bound via the placeholder form:
Enum.map([1, 2, 3], &(&1 * 10)) #=> [10, 20, 30]
4. Placeholder capture — partial application’s inline sugar. &(&1 + 10)
is a function whose 10 was fixed at creation; &1 remains variable. The
distinction to hold onto: in &(&1 + n) the current value of n is
captured (a closure over n), whereas in &(&1 + 10) the literal is simply
part of the expression — there is nothing to go stale.
From Erlang you know: all four ideas already exist in Erlang —
fun lists:max/1(capture),fun(X) -> X > Threshold end(closure),fun(B) -> Add(10, B) end(partial application). Elixir adds only the&shorthand with&1, &2…placeholders, which turns the partial-application pattern from a hand-written wrapper into a one-liner.
Reading &(...) — Placeholders, Arity, and Bound Values
The placeholder form confuses everyone on first sight. The trick is to
separate the two & roles hiding in &(&1 + &2):
- the outer
&says: “turn this expression into a function” &1,&2,&3are the arguments that function will receive
So &(&1 + &2) reads: “make a function whose body is first arg + second
arg” — exactly fn a, b -> a + b end:
iex> add = &(&1 + &2)
iex> add.(10, 20)
30
Two gotchas to internalize early. First, &1/&2 are not variables —
they are syntactic slots that exist only inside the &(...) expression, so
add.(&1, &2) is a compile error. Second, the highest placeholder number
is the arity:
iex> double = &(&1 * 2) # one placeholder → arity 1
iex> double.(10)
20
iex> triple = &{&1, &2, &3} # three placeholders → arity 3
iex> triple.(10, 20, 30)
{10, 20, 30}
So &(&1 + &2 + &3) compiles to fn a, b, c -> a + b + c end, and calling
it with two arguments raises BadArityError — same as calling any Erlang fun
with the wrong count.
Parentheses define the body clearly. & &1 + &2 happens to parse as
&(&1 + &2) (capture binds tighter than +), but & grabs a single
expression, and with mixed operators or nested calls the unparenthesized
form gets hard to read — and ambiguous to the parser in argument lists. Wrap
the body: &(&1 + &2). mix format enforces this for you.
The comparison worth memorizing — two ways to get the same function:
add = &(&1 + &2) # build a new anonymous function...
add = &Kernel.+/2 # ...or capture the EXISTING Kernel.+/2
add.(10, 20) #=> 30 either way
&Kernel.+/2 says “give me the function + with arity 2” — the /2 is the
arity suffix, the same notation as String.upcase/1 in docs. The placeholder
form builds the function fresh; the /arity form references one that already
exists.
Where this pays off daily — Enum callbacks and sorters:
iex> Enum.map([1, 2, 3, 4], &(&1 * 2)) #=> [2, 4, 6, 8]
iex> users = [%{name: "Bob", age: 30}, %{name: "Alice", age: 20}]
iex> Enum.sort_by(users, &(&1.age)) # fn u -> u.age end
[%{name: "Alice", age: 20}, %{name: "Bob", age: 30}]
And the tie back to the previous section: placeholders are the dynamic slots; anything else in the body is a bound value:
x = 10
fun = &(&1 + x) # &1 dynamic, x bound (a closure over the current value)
fun.(5) #=> 15
So &(&1 + &2) has two dynamic arguments, while &(&1 + x) has one dynamic
argument plus one bound value. The mental model: read &(...) as “make this
expression into a function,” then translate each &n to “the n-th argument.”
&(&1 * 2) → fn x -> x * 2 end. & &1.name → fn x -> x.name end. Once
that translation is automatic, the syntax stops being mysterious — it is
Elixir’s compact lambda notation.
Guards (when) — Same Idea, Richer Library
Guards work exactly like Erlang’s, joined by and/or (strict boolean) or
the relaxed &&/||. Kernel auto-imports ~40 guard-safe functions:
type checks (is_integer/1, is_binary/1, is_struct/1…), size checks
(byte_size/1, tuple_size/1, map_size/1, length/1), arithmetic
(div/2, rem/2, abs/1, round/1…), plus hd/1, tl/1, elem/2,
self(), node():
def drive(%User{age: age}) when age >= 16 do
:allowed
end
def classify(term) when is_binary(term), do: :text
def classify(term) when is_integer(term) and term > 0, do: :positive
You can compose your own guard-safe helpers with defguard — reusable guard
fragments that expand inline (so they stay guard-legal):
defmodule MyGuards do
defguard is_adult(age) when is_integer(age) and age >= 18
end
defmodule Voter do
import MyGuards
def check(age) when is_adult(age), do: {:ok, :vote}
def check(_age), do: {:error, :too_young}
end
Numbers: / Is Always Float Division
A classic stumble even for Erlang devs who assumed parity. Kernel docs are
explicit: / returns a float; integer division needs div/2, remainder
rem/2; power is **; both divisions by zero raise ArithmeticError:
iex> 5 / 2 #=> 2.5
iex> 5 / 1 #=> 5.0 ← always float, even when evenly divisible!
iex> div(5, 2) #=> 2
iex> rem(5, 2) #=> 1
iex> 2 ** 10 #=> 1024
iex> round(3.6) #=> 4 (Kernel — returns an integer)
iex> trunc(3.6) #=> 3
iex> Float.floor(3.6) #=> 3.0 (Float module — returns a float)
iex> Float.ceil(3.6) #=> 4.0
Equality: == vs ===
Same distinction as Erlang’s == vs =:= family, different symbols:
iex> 1 == 1.0 #=> true (numeric comparison across int/float)
iex> 1 === 1.0 #=> false (strict match comparison)
iex> 1 !== 1.0 #=> true
Translation line: map Erlang = (match) → Elixir =; map ==/!= →
same symbols; map =:=/=/= (exact) → ===/!==.
Pinning: Everywhere a Pattern Appears
^var reappears beyond the §2.7 gotcha — it is legal in every pattern
position where the name is in scope: case, receive, fn heads, for
generators, and nested matches:
expected = {:ok, :ready}
poll = fn -> {:ok, :ready} end
case poll.() do
^expected -> :unchanged # match AGAINST the earlier binding
other -> {:drifted, other}
end
listener = fn # pins close over the binding captured
^expected -> :exact # when the fn was created
_ -> :drifted
end
One asymmetry worth naming: pinning makes no sense in def heads — module-
level functions have no enclosing lexical scope to pin against. Erlang’s
f(X) when X =:= Expected muscle memory maps to guards over module
attributes (§2.1), not to ^.
Sigils — Literals With a Twist
Sigils build common literals concisely (all runnable):
iex> ~c"hello" # charlist — what Erlang calls "string"
~c"hello"
iex> ~s"hello #{1 + 1}" # string with interpolation
"hello 2"
iex> ~S"#{no_interp}" # raw string, no interpolation/escapes
"\#{no_interp}"
iex> ~w(a b c) # word list — splits on whitespace
["a", "b", "c"]
iex> ~r/\d+/ # Regex struct
~r/\d+/
iex> ~U[2026-08-25 12:00:00Z] |> DateTime.to_date()
~D[2026-08-25]
Mnemonic: lowercase sigils interpolate and process escapes (~s, ~c);
uppercase versions are raw (~S, ~C). Delimiters are interchangeable:
~w(...) ≡ ~w[...] ≡ ~w|...| — pick per readability.
Date/time sigils build calendar structs directly — no parsing, no stringly-typed dates:
iex> ~D[2026-08-25] # Date struct
~D[2026-08-25]
iex> ~T[09:41:00.123] # Time (microsecond precision)
~T[09:41:00.123]
iex> ~N[2026-08-25 09:41:00] # NaiveDateTime — no timezone attached
~N[2026-08-25 09:41:00]
iex> ~U[2026-08-25 09:41:00Z] # DateTime — UTC enforced at build time
~U[2026-08-25 09:41:00Z]
iex> ~w(read write)a # ~w takes a modifier for the element type
[:read, :write]
iex> ~w(1 2)s # s → strings (default); c → charlists; a → atoms
["1", "2"]
Interpolation vs io_lib:format
#{} inside strings calls to_string/1, which dispatches through the
String.Chars protocol (§5.2) — atoms, numbers, binaries and structs with an
implementation pass through; anything else raises:
iex> "n=#{40 + 2}"
"n=42"
iex> "#{:ok}" # atoms implement String.Chars
"ok"
iex> inspect({:ok, 1}) # inspect/1 handles ANY term
"{:ok, 1}"
For printf-style control, the Erlang machinery remains one atom away — format string in, iodata out:
iex> :io_lib.format("~s: ~.2f kg", ["cargo", 12.5]) |> IO.iodata_to_binary()
"cargo: 12.50 kg"
Rule of thumb: interpolation for gluing known-good values; inspect/1 when
debugging arbitrary terms; :io_lib.format when you need widths, precision,
or compatibility with APIs expecting format strings.
2.5 The Pipe Operator
The single most visible ergonomic change. Instead of nesting inside-out — where you read the last operation first:
Result = lists:sum( %% ③ outermost = LAST step
lists:map(fun(X) -> X * 2 end, %% ② middle
lists:filter(fun(X) -> X > 5 end,
lists:seq(1, 10)))). %% ① innermost = FIRST
You thread left-to-right, top-to-bottom, passing each result as the first argument of the next call:
flowchart LR
R["1..10<br/>(range)"] -->|"filter &(&1 > 5)"| A["[6, 7, 8, 9, 10]"]
A -->|"map &(&1 * 2)"| B["[12, 14, 16, 18, 20]"]
B -->|"sum()"| C["80"]
result =
1..10
|> Enum.filter(&(&1 > 5))
|> Enum.map(&(&1 * 2))
|> Enum.sum()
#=> 80
Mechanics worth internalizing once: x |> f(y) rewrites to f(x, y). That
works because Enum functions deliberately take the collection first —
argument order across the stdlib is designed for piping. Same semantics as
threading through staged variables in Erlang, but readable top to bottom.
You will see pipes everywhere; they are the ecosystem’s house style.
2.6 Quick Reference: Keyword Mapping
| Erlang | Elixir | Notes |
|---|---|---|
module | defmodule | |
export | public by default | Use defp for private |
import / include | import / alias / require | More granular, no headers |
define | @attribute | Module attributes |
if / case / receive | if / case / receive | Similar |
fun(X) -> ... end | fn x -> ... end | |
begin / end | do / end | |
; clause separator | none | Clauses separated by pattern |
. terminator | none | Line-based |
= match | = match | Same operator, same semantics |
record | defstruct | Structs are checked maps |
try/catch/after | try/rescue/catch/after | rescue for exceptions |
atoms 'my_atom' | :my_atom | Same runtime representation |
"string" (list of ints) | "string" (UTF-8 binary!) | See gotchas below |
2.7 Gotchas Specific to Erlang Developers
Each gotcha below has bitten every migrating Erlang dev at least once — better here than in production.
1. Strings are binaries by default.
This is THE gotcha. The word "string" means opposite things:
flowchart TD
Q{"double or single quotes?"}
Q -->|"#quot;abc#quot;"| BIN["UTF-8 BINARY<br/><<97, 98, 99>><br/>Elixir's default #quot;string#quot;<br/>≈ Erlang <<#quot;abc#quot;>>"]
Q -->|"'abc' (deprecated) or ~c#quot;abc#quot;"| CL["CHARLIST<br/>[97, 98, 99]<br/>list of codepoints<br/>≈ Erlang #quot;abc#quot;"]
iex> byte_size("abc") # binary: size in bytes
3
iex> "abc" == <<"abc">>
true
iex> ~c"abc" ++ ~c"d" # charlist: plain list ops work
~c"abcd"
Charlists exist mainly for Erlang interop (some OTP APIs want them) — reach
for ~c"" when you need them explicitly. Bare single-quoted literals like
'abc' still work, but Elixir emits a deprecation warning for them; write
~c"..." in new code and run mix format --migrate to convert an existing
codebase.
1b. Binaries are bit-precise, and mostly unchanged. If you parse
protocols, write codecs, or read binary_to_term payloads, this is the one
Elixir syntax that is nearly identical to Erlang — worth confirming rather
than relearning. Only the spellings change:
%% Erlang
<<Len:16/big-unsigned-integer, Rest/binary>> = Frame,
<<X:32/little-float>> = Body,
Bits = <<1:3, Rest2/bitstring>>.
# Elixir — same bytes, different punctuation
<<len::16, rest::binary>> = frame
<<x::little-float-32>> = body
<<1::size(3), rest2::bitstring>> = bits
Translation table for the parts you will actually type:
| Erlang | Elixir | Note |
|---|---|---|
T:8/integer-unsigned-big | T::8 | default is unsigned, big-endian |
T:16/little-unsigned-integer | T::little-unsigned-16 | endianness is a type |
T:32/float | T::float-32 | maps onto IEEE-754 single |
T:Len/binary | T::binary-size(len) | size driven by a pattern var |
T/utf8 | T::utf8 | unchanged; validated on match |
Rest/bitstring | Rest::bitstring | binary = byte-aligned, bitstring = not |
<<X:3, _:5>> = Bin | <<x::size(3), _::size(5)>> = bin | size() replaces N |
Two Elixir-specific hazards, both covered in depth in Ch 25:
- Size must be pinned.
<<x::size(n)>>in a pattern is deprecated as of Elixir 1.20 — write<<x::size(^n)>>. In a construction a barenis fine. binarymeans byte-aligned.<<1::3>>has a 3-bit tail, so matching it against::binaryfails. Pick::bitstringwhen the tail is not a whole byte.
Slicing has the same shape on both sides: binary_part(Bin, Pos, Len) →
binary_part/3 unchanged, or binary_slice(Bin, Pos, Len), or pattern-matched
slices via <<_::binary-size(pos), rest::binary>> = bin.
2. No semicolons or dots. Commas separate arguments; newlines separate expressions within blocks. Clause sequences are just consecutive heads.
3. Parentheses are optional — but keep them. Elixir lets you drop parens
on named calls (add 1, 2 parses fine) and on many zero-arity reads
(Node.self). House style — and mix format — keeps them (add(1, 2)),
because ambiguous-looking calls without parens trigger compiler warnings.
Coming from Erlang where parens are mandatory, the discipline transfers
unchanged: just write them.
4. Module names are CamelCase aliases, resolved at compile time. And the
escape hatch always works: :gen_server.start_link(...) — full Erlang
interop is direct, atoms-and-all.
5. = is always a match operator — and Elixir allows rebinding. This is
the single most important difference from Erlang, and it is why pinning
exists:
%% Erlang: one variable, one binding. The second assignment is badmatch.
X = 1,
X = 2. %% ** exception error: badmatch
iex> x = 1
1
iex> x = 2 # rebinds: no warning, no error
2
Inside a pattern, a bare variable still rebinds rather than comparing. So
%{status: expected, code: actual} will happily bind expected = :error
even if a variable named expected was already bound. To compare against an
existing value you must pin it:
iex> expected = :ok
iex> case result do
...> ^expected -> :matched # ^ pins: match AGAINST the bound value
...> _ -> :other # without ^, expected would REBIND
...> end
Erlang developers rarely need this because rebinding is impossible there; Elixir code that wants a comparison must say so explicitly. Ch 25 unpacks the full rule set, and Ch 30’s pitfall table calls this out as the #1 reflex to unlearn.
6. Keyword lists vs maps. Two key-value structures with different rules — choose by properties, not habit:
flowchart TD
Q{"what do you need?"} --> O["ordered · duplicate keys allowed<br/>keys are atoms · optional-arg style"] --> KL["KEYWORD LIST<br/>[a: 1, a: 2, b: 3]<br/>Keyword module"]
Q --> M["unique keys · arbitrary key terms<br/>fast lookup · pattern-matchable"] --> MAP["MAP<br/>%{a => 1} or %{a: 1}<br/>Map module"]
iex> [a: 1, a: 2, b: 3] # keyword list: duplicates fine — options rely on this
[a: 1, a: 2, b: 3]
iex> %{a: 1} == [{:a, 1}] # map ≠ keyword list — different types!
false
iex> Keyword.get([a: 1, b: 2], :a)
1
Options arguments (def f(opts \\ [])) are keyword lists by ecosystem
convention; anything needing pattern matching or uniqueness is a map.
7. / returns floats; div/rem for integers (§2.4).
8. Structural comparison everywhere. <, >, min/max compare raw
terms using the BEAM term order (Ch 01 §1.6) — so "b" < :atom is false
(bitstrings sort after everything) and sorting mixed types follows VM rules,
not domain rules. For domain-aware ordering, types ship semantic
comparators — e.g. Date.compare/2, Enum.sort(dates, Date).
9. Charlist or binary? Decide at the API boundary.
Both represent text; the choice falls out of who consumes it:
iex> "ab" <> "cd" # binaries concatenate with <>
"abcd"
iex> ~c"ab" ++ ~c"cd" # charlists concatenate with ++
'abcd'
iex> String.codepoints("héllo") # the String module = UTF-8 binaries
["h", "é", "l", "l", "o"]
Default to binaries — the whole Elixir ecosystem (Phoenix, Ecto, String)
speaks UTF-8 binaries. Reach for charlists only where OTP demands them:
some :code, :file, and port-facing APIs predate binaries, and older
Erlang libraries may hand you one back. Use ~c"..." literals or
to_charlist/1 at the boundary and convert immediately; inside your own
modules, one representation — binaries — wins.
Kernel Is the Default Environment
Everything above lives in the Kernel module — Elixir’s default environment.
Its functions and macros are auto-imported: you never write
Kernel.if/2. Two consequences worth knowing:
# Don't like a built-in? Exclude it per module:
import Kernel, except: [if: 2]
# Special forms (defmodule, def, fn, quote, case, =, ::, <<>>, alias,
# import, require...) live in Kernel.SpecialForms: always imported,
# can NEVER be excluded or overridden — they *are* the language.
The rest of the standard library builds outward in groups (per the Kernel
docs): built-in type modules (Atom, Map, List, Process…),
derived data types (Date, Keyword, Range, MapSet, Regex…),
system modules (IO, File, Path, System), protocols
(Enumerable, Inspect, String.Chars…) and process abstractions
(Agent, Task, GenServer, Supervisor, Registry). Chapter 5 covers
that last group.
2.8 A Complete Translation, End to End
Pull the dictionary together with one bounded stack. First in Erlang:
-module(stack).
-export([new/0, push/2, pop/1]).
new() -> [].
push(Stack, Item) -> [Item | Stack].
pop([]) -> {error, empty};
pop([Top | Rest]) -> {ok, Top, Rest}.
Same program in Elixir — notice every line pairing with its neighbor:
defmodule Stack do
def new, do: []
def push(stack, item), do: [item | stack]
def pop([]), do: {:error, :empty}
def pop([top | rest]), do: {:ok, top, rest}
end
iex> s = Stack.push(Stack.push(Stack.new(), 1), 2)
[2, 1]
iex> {:ok, value, _rest} = Stack.pop(s)
{:ok, 2, [1]}
iex> value
2
iex> Stack.pop([])
{:error, :empty}
Note the deliberate argument order: push takes its data first, so the
pipe works naturally — Stack.new() |> Stack.push(1) |> Stack.push(2) builds
the same [2, 1]. That first-argument convention behind |> (§2.5) is an
Enum-family design choice, not a language rule — but adopting it makes your
own APIs pipe-able for free.
Hold onto this pairing habit: read Elixir, mentally render the Erlang, spot-check against the compiler. Within a week the middle step goes silent and you are simply reading code.
Explore More
- Kernel docs — read once end-to-end; it IS the language surface
- Syntax reference — the complete grammar in one page
- Sigils guide — every sigil explained with examples
- Erlang Efficiency Guide: functions
— inlining, BIFs, and list comprehensions; explains the
&Kernel.is_atom/1 → & :erlang.is_atom/1result you can observe in §2.7 - Exercise: take a real
.erlmodule from your codebase and translate it using only §2.6’s table — then run both and diff behaviors (they should be identical modulo the gotchas above) - Exercise: write the same binary parser twice — once Erlang-flavoured, once using §2.7’s Elixir translation table — and confirm both produce identical bytes for an IP header with unusual IHL and total-length fields
Checkpoint
- Translate
-record(state, {pid, count = 0}).plus one accessor into Elixir. - Rewrite a three-deep nested
lists:chain using pipes. - What does
"abc"evaluate to at the BEAM level? And~c"abc"? - How do you call
lists:max/1from Elixir? - What does
10 / 4return? And how do you get2instead? - Which two values are falsy, and which operator would raise on them as
left-hand side:
&&orand? - In a
withclause, what happens when a<-pattern does not match the step’s return value? - Is
&(&1 * factor)a closure, a partial application, or both? What does it capture, and what happens to the resulting function iffactoris rebound afterwards?
Answers
defmodule State do @enforce_keys [:pid] defstruct [:pid, count: 0] end; accessor:def get_count(%State{count: c}), do: c.1..10 |> Enum.filter(&(&1 > 5)) |> Enum.map(&(&1 * 2)) |> Enum.sum()"abc"is a UTF-8 binary (<<97, 98, 99>>);~c"abc"is a charlist ([97, 98, 99]) — what Erlang calls a string. (Bare'abc'works but warns; use the~csigil.):lists.max(list)— any Erlang module is callable as:module.fun(args).10 / 4returns2.5;/always returns floats (raises on zero). Integer division:div(10, 4)→2.falseandnil. The strict operatorandraisesBadBooleanErrorgiven a non-boolean;&&accepts any truthy/falsy value.- Execution short-circuits into the
elseblock with the unmatched value (or returns that value unchanged if there is noelse). Matched steps bind and continue down the chain. - Both. It is a partial application whose multiplier comes from a closure
over
factor: the current binding is captured at creation, so rebindingfactorafterwards changes nothing — the function keeps multiplying by the old value (frozen snapshot, like an Erlangfunclosing over a variable).