Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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

ConceptErlangElixir
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 functionsNot exporteddefp 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:

  1. Visibility inverts. Erlang is private-by-default (-export opts in); Elixir is public-by-default (defp opts out). Idiomatic Elixir still keeps most functions defp — treat public surface as deliberate API design.
  2. Module names are aliases. MyApp.Utils is sugar for the atom :"Elixir.MyApp.Utils"; nested naming is convention plus aliasing, covered in §2.2. There are no dotted atoms like my_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

ConceptErlangElixir
Define module-module(name).defmodule Name do ... end
Alias long nameManualalias MyApp.LongModule, as: Short
Import functionsNot built-inimport 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.Module lets you write Module.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 -define successor (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 3 is 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):

ConceptErlang (Records)Elixir (Structs)
Definition-record(user, {name, age}).defstruct [:name, :age] inside a module
Creation#user{name = "Alice"}%User{name: "Alice"}
AccessUser#user.nameuser.name
UpdateUser#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 keysNoYes (@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:

  1. One struct per module — the module becomes home to related functions (constructors, domain logic), not just data.
  2. @enforce_keys turns “forgot to set the field” into a compile-time crash instead of a runtime undefined.
  3. 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 constructClassElixir home
throw(Term):throwthrow(term) + catch arm
exit(Reason):exitexit(reason) + catch :exit, r ->
erlang:error(R), badmatch, …:errorraise + 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 <- expr runs expr and matches the result against pattern. A match binds and continues; a mismatch short-circuits into else carrying the unmatched value (not an error).
  • Plain expr lines (no <-) execute for effect or assert via = — a failed assert raises MatchError, which is correct for programmer errors.
  • Without an else block, a falling-through value is returned as-is — convenient when every step already speaks {:error, _}.
  • else arms are ordinary case clauses: 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:

ConceptExampleWhat’s captured/bound?
Function capture&String.upcase/1The function itself, no args
Closurefn x -> x + n endVariable n from outer scope
Partial applicationfn x -> add.(10, x) endArgument 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, &3 are 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

ErlangElixirNotes
moduledefmodule
exportpublic by defaultUse defp for private
import / includeimport / alias / requireMore granular, no headers
define@attributeModule attributes
if / case / receiveif / case / receiveSimilar
fun(X) -> ... endfn x -> ... end
begin / enddo / end
; clause separatornoneClauses separated by pattern
. terminatornoneLine-based
= match= matchSame operator, same semantics
recorddefstructStructs are checked maps
try/catch/aftertry/rescue/catch/afterrescue for exceptions
atoms 'my_atom':my_atomSame 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:

ErlangElixirNote
T:8/integer-unsigned-bigT::8default is unsigned, big-endian
T:16/little-unsigned-integerT::little-unsigned-16endianness is a type
T:32/floatT::float-32maps onto IEEE-754 single
T:Len/binaryT::binary-size(len)size driven by a pattern var
T/utf8T::utf8unchanged; validated on match
Rest/bitstringRest::bitstringbinary = byte-aligned, bitstring = not
<<X:3, _:5>> = Bin<<x::size(3), _::size(5)>> = binsize() 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 bare n is fine.
  • binary means byte-aligned. <<1::3>> has a 3-bit tail, so matching it against ::binary fails. Pick ::bitstring when 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/1 result you can observe in §2.7
  • Exercise: take a real .erl module 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

  1. Translate -record(state, {pid, count = 0}). plus one accessor into Elixir.
  2. Rewrite a three-deep nested lists: chain using pipes.
  3. What does "abc" evaluate to at the BEAM level? And ~c"abc"?
  4. How do you call lists:max/1 from Elixir?
  5. What does 10 / 4 return? And how do you get 2 instead?
  6. Which two values are falsy, and which operator would raise on them as left-hand side: && or and?
  7. In a with clause, what happens when a <- pattern does not match the step’s return value?
  8. Is &(&1 * factor) a closure, a partial application, or both? What does it capture, and what happens to the resulting function if factor is rebound afterwards?
Answers
  1. defmodule State do @enforce_keys [:pid] defstruct [:pid, count: 0] end; accessor: def get_count(%State{count: c}), do: c.
  2. 1..10 |> Enum.filter(&(&1 > 5)) |> Enum.map(&(&1 * 2)) |> Enum.sum()
  3. "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 ~c sigil.)
  4. :lists.max(list) — any Erlang module is callable as :module.fun(args).
  5. 10 / 4 returns 2.5; / always returns floats (raises on zero). Integer division: div(10, 4) → 2.
  6. false and nil. The strict operator and raises BadBooleanError given a non-boolean; && accepts any truthy/falsy value.
  7. Execution short-circuits into the else block with the unmatched value (or returns that value unchanged if there is no else). Matched steps bind and continue down the chain.
  8. Both. It is a partial application whose multiplier comes from a closure over factor: the current binding is captured at creation, so rebinding factor afterwards changes nothing — the function keeps multiplying by the old value (frozen snapshot, like an Erlang fun closing over a variable).

Next: Chapter 3 — Tooling: From rebar3 to Mix