Show Menu
Cheatography

Just another Elixir cheat sheet

Enum types

I need...
Function
Example
BigO
Execute without return
Enum.e­ach/2
Enum.e­ach­([1­,2,3], &I­O.p­uts/1)
O(n)
Transform each element
Enum.map/2
Enum.m­ap(­[1,­2,3], &(­&1 * 2)) # [2,4,6]
O(n)
Filter elements
Enum.f­ilter/2
Enum.f­ilt­er(­[1,­2,3], &(­&1 > 1)) # [2,3]
O(n)
Accumulate a value
Enum.r­educe/2
Enum.r­edu­ce([1, 2, 3, 4], fn x, acc -> x * acc end)
O(n)
Find a value
Enum.f­ind/2
Enum.f­ind­([1­,2,3], &(­&1 > 1)) # 2
O(n) (worst case)
Check if all match condition
Enum.a­ll?/2
Enum.a­ll?­([2­,4,6], &r­em(­&1, 2) == 0) # true
O(n) (worst case)
Check if exists inside
Enum.m­emb­er?/2
Enum.m­emb­er?­([1­,2,3], 2) # true
O(n)

Data Structure Types

Data Structure
Access Compex
Observ­ations
list
O(n)
sorted, duplicated keys
tupple
O(1)
map
O(1) map > 32 / O(n) map < 32
unsorted, no key duplic­ation
keyword list
O(n)
Inserting with prepend is O(1)
Maps < 32 are sorted lists
Maps > 32 are hash-tree (HAMT)
Lists, when insert prepend for O(1), append is O(n)

Sort Algoritms

Name
Time Complex
Comments
Merge Sort
🔹 O(n log n) / O(n log n) / O(n log n)
Recomm­ended in Elixir (recursive and stable)
Insertion Sort
✅ O(n) / 🔺 O(n²) / O(n²)
Good for small or semi-o­rdered lists
Radix Sort
O(nk) / O(nk) / O(nk)
Very fast on small integers
Bubble Sort
✅ O(n) / 🔺 O(n²) / ❌ O(n²)
Ineffi­cient, useful only for small or already sorted lists
Selection Sort
🔺 O(n²) / O(n²) / O(n²)
Simple, but slow
QuickSort
✅ O(n log n) / O(n log n) / ❌ O(n²)
Better than MergeSort on average, but can degrade to O(n²)
Heap Sort
O(n log n) / O(n log n) / O(n log n)
Counting Sort
O(n + k) / O(n + k) / O(n + k)
Only works with small numbers and limited range
Bucket Sort
O(n + k) / O(n + k) / O(n²)
Useful if data is evenly distri­buted
Avoid:
QuikSort because we can get O(n²) if the list is already sorted.
Insertion (O(n²)) → If the list is inverted.

Merge Sort


defmodule MergeSort do
  def sort([]), do: []
  def sort([x]), do: [x]

  def sort(list) do
    midpoint = div(length(list), 2)
    {left, right} = Enum.split(list, midpoint)
    
    new_left = sort(left)
    new_right = sort(right)
    
    merge(new_left, new_right)
  end

  def merge(left, []), do: left
  def merge([], right), do: right

  def merge([l | left], [r | right]) when l <= r do
    [l | merge(left, [r | right])]
  end

  def merge([l | left], [r | right]) do
    [r | merge([l | left], right)]
  end
end


MergeSort.sort([2,4,6,7,1,2,3,5])

Insertion Sort


defmodule Sort do
  def insert([], x), do: [x]

  def insert([h | t], x) when x <= h, do: [x, h | t]  # Insert before if is lower 
  
  def insert([h | t], x), do: [h | insert(t, x)]  # Continue searching if is greater

  def insertion_sort([]), do: []
  
  def insertion_sort([h | t]) do
    sorted_tail = insertion_sort(t)
    insert(sorted_tail, h)
  end
end

Sort.insertion_sort([3, 1, 4, 2])

Detect Anagram


defmodule Anagram do
  def anagram?(word1, word2) do
    Enum.sort(String.graphemes(word1)) == Enum.sort(String.graphemes(word2))
  end
end

IO.inspect(Anagram.anagram?("listen", "silent"))  # true
O(n log n) because Enum.sort

Palindrome


defmodule Palindrome do
  def is_polindrome?(word) do
  word_to_charlist = to_charlist(word)
  (word_to_charlist == Enum.reverse(word_to_charlist))
  end
end

Palindrome.is_polindrome?("acbca")
Use recursive option is less perfor­mance. It uses List.l­ast/1 and Enum.d­rop/2 (O(n) each), making the complexity O(n²).

Fibonacci


defmodule Fibonacci do
  def fib(n), do: fib(n, 0, 1)

  defp fib(0, a, _b), do: a
  defp fib(n, a, b), do: fib(n - 1, b, a + b)
end

IO.inspect(Fibonacci.fib(10))  # => 55
O(n)

Fast Enum Reference

Acumulate
reduce
Return in map or diff type than map
reduce
Return list
map
Discard / Clean
filter

Liveview callbacks

mount
handle­_event
clicks, forms, keys, hooks.
handle­_info
messages from other processes (send)
handle­_params
Respond to URL changes

Actor model

The actor model is a concur­rency paradigm in which processes (called actors) commun­icate exclus­ively through message passing, without sharing memory.

The actor model uses a FIFO queue-like structure to process messages, but encaps­ulated in each actor.
It is not a tradit­ional queue because each actor is an autonomous and concurrent system.

GenServer Callback

init
handle­_call
handle­_cast
handle­_info
code_c­hange
Hot code update
terminate
 

Best for inserts / updates

Lists (Prepend)
[new_item | list]
Maps insert
Map.put O(1) except hash collisions
Maps update
%{map | a: 42} better than Map.put
Keyword List (Prepend)
[{:key, val} | kw_list]

Process Commun­ication Elixir­/Erlang

Interp­rocess commun­ication in Erlang and Elixir is based on the actor model and is completely asynch­ronous. Each process is lightw­eight, running on the BEAM virtual machine, and has its own state and message queue. Processes do not share memory, allowing for lock-free concur­rency and fault tolerance.

1-Erlang cookie is same in 2 nodes
2-Node1 ask for the Node2 port using EPMD
3-Node 1 send a message to the EDP (Erlang Distri­bution Protocol)

Difference with process messaging in Java and why is better?
Because Java uses OS threads, these can share memory, every thread use stack and OS resources.
 

Strings to charlist


#Directly using sigil ~c
~c"abc"

#from symbol
def foo(name) do
  to_charlist(name)
end

Imports, alias, use, require

use
Extend modules and add functi­onality
use GenServer
require
Use macros from another module
require Logger
import
Use functions without module prefix
import Enum, only: [map: 2]
alias
Short modules names
alias MyApp.F­oo.Foo2

Difference GenServer VS GenState

GenServer has state and response to casts.
GenState is data-flow with backpresure.
 

String to List ("AB­"­=>[­"­A", "­B"])


String.graphemes("AB")

Interfaces with Elixir (polym­orp­hism)

first defines the @callbacks in an interface module...

Then implement in a module using @behavior

Lastly, when we "­ove­rri­de" a function defined in interface or which has a callback use
@impl true

inheri­tance in Elixir

The most similar to "­inh­eri­tan­ce" is to use the
use
macro. This extends functions in the module.

OBAN vs EXq

Caract­erist
OBAN
Exq
DB
Postgres
Redis
Distri­buted
Multi-node
Needs Redis Cluster
Retries
Config­urable with backoff
Less flexible
Scalable
Excelent for big systems
Good, but depends on Redis
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Elixir Cheat Sheet