Getting Started
4 snippetsYour first steps with Elixir
Hello World
IO.puts("Hello, World!")Comments
# Single line comment
@moduledoc """
Module documentation
"""Run Code
elixir script.exs # Run script
iex # Interactive shell
iex -S mix # Shell with projectCreate Project
mix new my_app
mix new my_app --sup # With supervisorBasic Types
5 snippetsData types and literals
Numbers
42 # Integer
3.14 # Float
0b1010 # Binary (10)
0o777 # Octal (511)
0xFF # Hex (255)Atoms
:ok
:error
:hello_world
true # Same as :true
false # Same as :false
nil # Same as :nilStrings
"Hello, World!"
"Hello, #{name}!" # Interpolation
~s(String with "quotes")Charlists
'hello' # List of integers
[104, 101, 108, 108, 111] # SameBooleans
true and false # true
true or false # true
not true # falseCollections
5 snippetsLists, tuples, and maps
List
[1, 2, 3]
[1 | [2, 3]] # Prepend
[1, 2] ++ [3, 4] # Concat
[1, 2, 3] -- [2] # Subtract
hd([1, 2, 3]) # 1 (head)
tl([1, 2, 3]) # [2, 3] (tail)Tuple
{:ok, "value"}
{:error, reason}
elem({:a, :b, :c}, 1) # :b
put_elem(tuple, 1, :x)Map
%{name: "John", age: 30}
%{"key" => "value"}
map[:name] # "John"
map.name # "John" (atom keys)
%{map | age: 31} # UpdateKeyword List
[name: "John", age: 30]
[{:name, "John"}, {:age, 30}] # SameStruct
defmodule User do
defstruct [:name, :age]
end
%User{name: "John", age: 30}Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Pattern Matching
4 snippetsMatch and destructure data
Basic Match
x = 1
{a, b} = {1, 2}
[head | tail] = [1, 2, 3]
%{name: name} = %{name: "John"}Pin Operator
x = 1
^x = 1 # Match against value of x
^x = 2 # ** (MatchError)Ignore
{_, second} = {1, 2}
[head | _] = [1, 2, 3]Guards
case value do
x when x > 0 -> "positive"
x when x < 0 -> "negative"
_ -> "zero"
endControl Flow
4 snippetsConditionals and pattern matching
Case
case value do
{:ok, result} -> result
{:error, _} -> "error"
_ -> "unknown"
endCond
cond do
x > 10 -> "big"
x > 5 -> "medium"
true -> "small"
endIf/Unless
if condition do
"true"
else
"false"
end
unless condition, do: "false"With
with {:ok, a} <- fetch_a(),
{:ok, b} <- fetch_b(a) do
{:ok, a + b}
else
{:error, reason} -> {:error, reason}
endFunctions
5 snippetsDefine and use functions
Named Function
defmodule Math do
def add(a, b) do
a + b
end
def add(a, b, c), do: a + b + c
endPrivate Function
defp helper(x) do
x * 2
endAnonymous Function
add = fn a, b -> a + b end
add.(1, 2) # 3
# Shorthand
add = &(&1 + &2)
add.(1, 2) # 3Default Args
def greet(name \\ "World") do
"Hello, #{name}!"
endMultiple Clauses
def factorial(0), do: 1
def factorial(n), do: n * factorial(n - 1)Pipe Operator
2 snippetsChain function calls
Basic Pipe
"hello world"
|> String.upcase()
|> String.split()
# ["HELLO", "WORLD"]With Arguments
[1, 2, 3]
|> Enum.map(&(&1 * 2))
|> Enum.filter(&(&1 > 2))
|> Enum.sum()
# 10Enum Module
6 snippetsWork with collections
Map
Enum.map([1, 2, 3], fn x -> x * 2 end)
# [2, 4, 6]Filter
Enum.filter([1, 2, 3, 4], &(rem(&1, 2) == 0))
# [2, 4]Reduce
Enum.reduce([1, 2, 3], 0, &(&1 + &2))
# 6Find
Enum.find([1, 2, 3], &(&1 > 1))
# 2All/Any
Enum.all?([2, 4, 6], &(rem(&1, 2) == 0)) # true
Enum.any?([1, 2, 3], &(&1 > 2)) # trueSort
Enum.sort([3, 1, 2]) # [1, 2, 3]
Enum.sort([3, 1, 2], :desc) # [3, 2, 1]Processes
4 snippetsConcurrent programming
Spawn
pid = spawn(fn -> IO.puts("Hello") end)
Process.alive?(pid)Send/Receive
send(self(), {:hello, "world"})
receive do
{:hello, msg} -> IO.puts(msg)
after
1000 -> IO.puts("timeout")
endTask
task = Task.async(fn -> expensive_work() end)
result = Task.await(task)Agent
{:ok, agent} = Agent.start_link(fn -> 0 end)
Agent.get(agent, & &1) # 0
Agent.update(agent, &(&1 + 1))