Show Menu
Cheatography

Elixir Cheat Sheet (DRAFT) by

Elixir Cheat Sheet 2023

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Hello world

# hello.exs
defmodule Greeter do
  def greet(name) do
    message = "Hello, " <> name <> "!"
    IO.puts message
  end
end

Greeter.greet("world")
elixir hello.exs
# Hello, world!

Pattern matching

user = %{name: "Tom", age: 23}
%{name: username} = user
This sets username to "­Tom­".

If

if false do
  "This will never be seen"
else
  "This will"
end

Types (Primi­tives)

nil
Nil/null
true / false
Boolean
?a
Integer (ASCII)
23
Integer
3.14
Float
'hello'
Charlist
<<2, 3>>
Binary
"­hel­lo"
Binary string
:hello
Atom
[a, b]
List
{a, b}
Tuple
%{a: "­hel­lo"}
Map
%MyStr­uct{a: "­hel­lo"}
Struct
fn -> ... end
Function

Modules (Impor­ting)

require Redux # compiles a module
import Redux # compiles, and you can use without the
Redux.
prefix

use Redux # compiles, and runs Redux._­_u­sin­g__/1
use Redux, async: true

import Redux, only: [dupli­cate: 2]
import Redux, only: :functions
import Redux, only: :macros

import Foo.{Bar, Baz}
 

Maps

user = %{
  name: "John",
  city: "Melbourne"
}
IO.puts "­Hello, " <> user.name

Variables

age = 23

Pattern matching in functions

ef greet(%{name: username}) do
  IO.puts "Hello, " <> username
end

user = %{name: "Tom", age: 23}
Pattern matching works in function parameters too.

Case

case {1, 2, 3} do
  {4, 5, 6} ->
    "This clause won't match"
  {1, x, 3} ->
    "This will match and bind x to 2"
  _ ->
   "This will match any value"
end

With

case Users.create_user(attrs) do
  {:ok, user} -> ...
  {:error, changeset} -> ...
end

with {:ok, user} <- Users.create_user(attrs) do
  ...
else
  {:error, changeset} -> ...
end
 

Lists

users = [ "Tom", "Dick", "Harry" ]
 
Enum.map(users, fn user ->
  IO.puts "Hello " <> user
end)

Piping

source
|> transform(:hello)
|> print()
 
# Same as:
print(transform(source, :hello))
These two are equiva­lent.

Cond

cond do
  1 + 1 == 3 ->
    "I will never be seen"
  2 * 5 == 12 ->
    "Me neither"
  true ->
    "But I will (this is essentially an else)"
end

Errors

try do
  throw(:hello)
catch
  message -> "Got #{message}."
after
  IO.puts("I'm the after clause.")
end

Type checks

is_atom/1
is_bin­ary/1
is_nil/1
is_bit­str­ing/1
is_list/1
is_num­ber/1
is_boo­lean/1
is_map/1
is_pid/1
is_fun­ction/1
is_tuple/1
is_port/1
is_fun­ction/2
 
is_ref­ere­nce/1
is_int­eger/1
is_float/1

Operators

left != right # equal
left !== right # match
left ++ right # concat lists
left <> right # concat string­/binary
left =~ right # regexp