Chuyển đến nội dung

Bài 48 · Practice and Review

Elixir Cheat Sheet

A one-page Elixir cheat sheet: types, operators, pattern matching, Enum, strings, processes, OTP behaviours and the most useful Mix commands.

This page is a quick reference for the Elixir you use every day. It does not teach the ideas from scratch: each section links to the lesson that does. Keep it open while you write code, and use h Module.function in IEx (see Installing Elixir and Using IEx) for the full documentation of any function.

All Elixir blocks are read-only, because Elixir is not installed on this site. Two small JavaScript stand-ins at the end let you play with the pipe operator and pattern matching idea.

Remember these five

Immutable Functions return new values.
Match = is a pattern match, not assignment.
Pipe a |> f() is f(a).
Messages Processes share nothing. Supervisors restart them.
1 / 2

Basic types

Type Examples Notes
Integer 42, 1_000_000, 0xFF, 0b1010 Arbitrary precision
Float 3.14, 1.0e10 64-bit
Atom :ok, :error, true, false, nil true, false and nil are atoms
String "héllo", "a #{1 + 1}" UTF-8 binary
Charlist ~c"abc" List of code points
Tuple {:ok, 1} Fixed size, fast access
List [1, 2, 3] Linked list
Keyword list [a: 1, b: 2] List of {atom, value}
Map %{"a" => 1}, %{a: 1} Key-value, any key
Struct %User{name: "Ada"} Named map with fixed keys
Range 1..10, 1..10//2 Lazy, with optional step
Function fn x -> x * 2 end, &(&1 * 2) Call with f.(1)

Only false and nil are falsy. See Basic Types and Strings and Binaries.

Operators

Operator Meaning
+ - * / Arithmetic (/ always returns a float)
div/2, rem/2 Integer division and remainder
==, !=, ===, !== Equality (=== is strict about 1 vs 1.0)
< > <= >= Comparison; any two terms can be compared
and or not Boolean only on the left
&& || ! Any value, truthiness
<> String concatenation
++, -- List add and subtract (right-associative)
in Membership: x in [1, 2]
|> Pipe
^ Pin in a pattern

See Operators and Comparison.

Pattern matching

ELIXIR
{a, b} = {1, 2}              # a = 1, b = 2
[head | tail] = [1, 2, 3]    # head = 1, tail = [2, 3]
%{name: name} = %{name: "Ada", age: 36}
{:ok, value} = {:ok, 42}
^a = 1                       # pinned: matches only if a is 1
[first, _, third] = [1, 2, 3]
"Hello, " <> rest = "Hello, Ada"   # rest = "Ada"

A failed match raises MatchError. The same patterns work in function heads, case, receive, with, for and fn. See Pattern Matching: The = Operator.

Control flow

ELIXIR
if x > 0, do: "positive", else: "other"
unless done?, do: run()

cond do
  n < 0 -> :negative
  n == 0 -> :zero
  true -> :positive
end

case File.read("a.txt") do
  {:ok, text} -> text
  {:error, reason} -> "failed: #{reason}"
end

with {:ok, a} <- fetch(:a),
     {:ok, b} <- fetch(:b) do
  {:ok, a + b}
else
  {:error, reason} -> {:error, reason}
end

Guards (when) allow only a safe set of expressions, such as comparisons, is_integer/1, is_binary/1, is_list/1, in, length/1 and map_size/1. See Conditionals and Multiple Clauses and Guards.

Functions and modules

ELIXIR
defmodule Math do
  @moduledoc "Small helpers."

  def square(x), do: x * x                  # public
  defp secret(x), do: x + 1                 # private

  def greet(name \\ "world"), do: "Hello, #{name}"

  def sign(n) when n < 0, do: :neg
  def sign(0), do: :zero
  def sign(_), do: :pos
end

add = fn a, b -> a + b end
add.(1, 2)
Enum.map([1, 2, 3], &(&1 * 2))   # capture: [2, 4, 6]
Enum.map([1, 2, 3], &Math.square/1)

A function is identified by name and arity: square/1. See Functions and Modules.

Pipe and recursion

ELIXIR
"  Hello World "
|> String.trim()
|> String.downcase()
|> String.split(" ")        # ["hello", "world"]

def sum([]), do: 0
def sum([h | t]), do: h + sum(t)

defp do_sum([], acc), do: acc          # tail-recursive form
defp do_sum([h | t], acc), do: do_sum(t, acc + h)

See The Pipe Operator and Recursion and Tail Calls.

Lists, maps and structs

ELIXIR
[0 | [1, 2]]                 # prepend (fast): [0, 1, 2]
[1, 2] ++ [3]                # append (copies the left list)
hd([1, 2, 3]); tl([1, 2, 3]) # 1; [2, 3]
elem({:a, :b}, 1)            # :b

map = %{name: "Ada", age: 36}
map.name                     # "Ada" (key must exist)
map[:email]                  # nil (Access, safe)
%{map | age: 37}             # update an existing key
Map.put(map, :email, "[email protected]")
Map.get(map, :x, :default)
Map.merge(map, %{age: 1})
Map.delete(map, :age)

defmodule User do
  @enforce_keys [:name]
  defstruct [:name, role: :member]
end

%User{name: "Ada"}

See Tuples and Lists and Maps and Structs.

Enum, Stream and for

Task Call
Transform Enum.map(list, fn x -> x * 2 end)
Keep or drop Enum.filter/2, Enum.reject/2
Fold Enum.reduce(list, 0, fn x, acc -> x + acc end)
Sum, count, min, max Enum.sum/1, Enum.count/1, Enum.min/1, Enum.max/1
Sort Enum.sort/1, Enum.sort_by(list, & &1.age, :desc)
Group and count Enum.group_by/2, Enum.frequencies/1
Combine Enum.zip/2, Enum.chunk_every/2, Enum.flat_map/2
Find Enum.find/2, Enum.any?/2, Enum.all?/2, Enum.member?/2
First elements Enum.take/2, Enum.drop/2, Enum.at/2
Running results Enum.scan/2
Lazy version Stream.map/2, Stream.filter/2, Stream.take/2, then an Enum call
ELIXIR
for x <- 1..5, rem(x, 2) == 1, do: x * x          # [1, 9, 25]
for {k, v} <- %{a: 1}, into: %{}, do: {k, v + 1}  # %{a: 2}

See The Enum Module, Comprehensions with for and Lazy Processing with Stream.

Strings, regex and sigils

ELIXIR
String.length("héllo")            # 5
String.upcase("abc")              # "ABC"
String.split("a,b,c", ",")        # ["a", "b", "c"]
String.replace("a-b", "-", "+")   # "a+b"
String.contains?("elixir", "xi")  # true
String.slice("elixir", 0, 3)      # "eli"

~w(red green blue)                # ["red", "green", "blue"]
~r/(\d+)-(\d+)/                   # regex
Regex.run(~r/(\d+)-(\d+)/, "10-20")   # ["10-20", "10", "20"]
~D[2026-01-31]                    # a Date

See Sigils and Regular Expressions.

Errors

ELIXIR
{:ok, result}  = ...     # success convention
{:error, reason} = ...   # failure convention

try do
  raise ArgumentError, "bad input"
rescue
  e in ArgumentError -> e.message
after
  cleanup()
end

File.read!("missing.txt")        # raises File.Error; the ! variant raises

Functions named name! raise on failure; name returns an {:ok, _} or {:error, _} tuple. See Error Handling.

Processes and OTP

ELIXIR
pid = spawn(fn -> receive do msg -> IO.inspect(msg) end end)
send(pid, :hello)
self()                       # current pid
Process.alive?(pid)
Process.monitor(pid)         # get {:DOWN, ...} when it ends
spawn_link(fn -> ... end)    # linked: crashes propagate

Task.async(fn -> work() end) |> Task.await()
{:ok, agent} = Agent.start_link(fn -> 0 end)
Agent.update(agent, &(&1 + 1))
Agent.get(agent, & &1)
ELIXIR
defmodule Counter do
  use GenServer

  def start_link(n), do: GenServer.start_link(__MODULE__, n, name: __MODULE__)
  def inc, do: GenServer.cast(__MODULE__, :inc)
  def get, do: GenServer.call(__MODULE__, :get)

  @impl true
  def init(n), do: {:ok, n}
  @impl true
  def handle_cast(:inc, n), do: {:noreply, n + 1}
  @impl true
  def handle_call(:get, _from, n), do: {:reply, n, n}
end

children = [{Counter, 0}]
Supervisor.start_link(children, strategy: :one_for_one)
Concept Remember
call Synchronous, waits for a reply (5 s default)
cast Asynchronous, returns :ok immediately
handle_info/2 Plain messages and :DOWN
:one_for_one Restart only the failed child
:one_for_all Restart all children
:rest_for_one Restart the failed child and the later ones
max_restarts / max_seconds Give up if restarts exceed the limit
ETS In-memory tables for fast shared reads (:ets.new/2)

See Processes and Message Passing, GenServer, Supervisors and Supervision Trees, Tasks and Parallel Work and ETS, Registry and Application State.

Mix and tooling

Command Purpose
iex / iex -S mix Interactive shell (with your project loaded)
elixir script.exs Run a script
mix new my_app --sup New project with a supervision tree
mix deps.get Fetch dependencies from Hex
mix compile Compile
mix test Run ExUnit tests (mix test path:line for one test)
mix format Format code
mix run -e "IO.puts(1)" Run an expression in the project
mix docs Build documentation (with ExDoc)
MIX_ENV=prod mix release Build a release

In IEx: h Enum.map, i value (inspect), r Module (recompile), v() (last value). See Mix: Creating and Managing Projects and Testing with ExUnit.

Play with the ideas

The pipe operator inserts the left value as the first argument of the next call. This JavaScript stand-in makes that rule visible:

JS A pipe function (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Now a tiny matcher that mimics {:ok, value} versus {:error, reason} clauses. JavaScript has no built-in pattern matching, so this stand-in checks a tag by hand:

JS Matching tagged tuples (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does a |> f(b) expand to?

    The pipe operator inserts the left-hand value as the first argument of the call.
  2. 2. Which call adds an element to the front of a list cheaply?

    Prepending creates one new cell pointing at the old list; appending copies the left list.
  3. 3. Which GenServer function waits for a reply?

    call is synchronous and times out after 5 seconds by default; cast returns immediately.
  4. 4. What does a function name ending in ! usually mean?

    By convention File.read!/1 raises while File.read/1 returns an ok or error tuple.

Summary

  • Types: atoms, tuples, lists, maps and structs; only false and nil are falsy.
  • = matches patterns; use ^ to pin, and patterns work in function heads, case, with and for.
  • Enum is eager and Stream is lazy; prepend to lists and avoid repeated appends.
  • Processes communicate with messages; GenServer, Agent and Task wrap common patterns, and supervisors restart failed children.
  • Mix builds, tests and releases projects.

Back to the start: What Is Elixir?.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.