Elixir Quick Reference
Pipe Operator
" HELLO "
|> String.trim()
|> String.downcase()
|> String.split(" ")
[1, 2, 3, 4, 5]
|> Enum.filter(&(rem(&1, 2) == 0))
|> Enum.map(&(&1 * 10))
|> Enum.sum() # 60
Pattern Matching
# Basic match
{:ok, result} = {:ok, 42}
[head | tail] = [1, 2, 3]
# Function clauses
defmodule Math do
def factorial(0), do: 1
def factorial(n) when n > 0, do: n * factorial(n - 1)
end
# Case expression
case File.read("file.txt") do
{:ok, content} -> process(content)
{:error, reason} -> IO.puts("Error: #{reason}")
end
Concurrency (Processes)
# Spawn a process
pid = spawn(fn -> IO.puts("Hello from process") end)
# Send and receive messages
send(pid, {:message, "hello"})
receive do
{:message, msg} -> IO.puts("Got: #{msg}")
after 5000 -> IO.puts("Timeout")
end
# Task (async operation)
task = Task.async(fn -> heavy_computation() end)
result = Task.await(task, 10_000)
GenServer
defmodule Counter do
use GenServer
def start_link(initial), do: GenServer.start_link(__MODULE__, initial)
def increment(pid), do: GenServer.cast(pid, :increment)
def get(pid), do: GenServer.call(pid, :get)
@impl true
def init(state), do: {:ok, state}
@impl true
def handle_cast(:increment, state), do: {:noreply, state + 1}
@impl true
def handle_call(:get, _from, state), do: {:reply, state, state}
end
Mix Commands
| Command | Description |
|---|---|
| mix new app_name | Create new project |
| mix deps.get | Install dependencies |
| mix compile | Compile project |
| mix test | Run tests |
| iex -S mix | Interactive REPL with project |