← docs.speechwave.live

Pipe operator and Enum cheatsheet

Pipe operator |>

# Rule: left result becomes the FIRST argument on the right
x |> f(a, b)   ≡   f(x, a, b)

# Chain reads top-to-bottom
data
|> step_one()
|> step_two(extra_arg)
|> step_three()

Capture operator &

ShorthandExpands to
& &1.namefn x -> x.name end
&(&1 + &2)fn x, y -> x + y end
&String.upcase/1fn x -> String.upcase(x) end
&to_string/1fn x -> to_string(x) end

Enum: most used functions

ElixirRubyReturns
Enum.map(list, fun).maplist
Enum.filter(list, fun).selectlist
Enum.reject(list, fun).rejectlist
Enum.find(list, fun).find / .detectelement or nil
Enum.reduce(list, acc, fun).inject / .reduceaccumulator
Enum.group_by(list, fun).group_bymap
Enum.sort_by(list, fun).sort_bylist
Enum.flat_map(list, fun).flat_maplist
Enum.count(list).count / .lengthinteger
Enum.any?(list, fun).any?boolean
Enum.all?(list, fun).all?boolean
Enum.each(list, fun).each:ok
Enum.into(enum, collectable).to_h / .to_acollectable
Enum.zip(list_a, list_b).ziplist of tuples

Map module: key-value operations

FunctionDoes
Map.get(map, key)Get value, returns nil if missing
Map.get(map, key, default)Get value with default
Map.put(map, key, value)Returns new map with key set
Map.delete(map, key)Returns new map without key
Map.merge(map1, map2)Merge maps (map2 wins on conflicts)
Map.keys(map)List of keys
Map.values(map)List of values
Map.new(enum, fun)Build map from enumerable
Map.fetch(map, key){:ok, val} or :error

Maps are immutable, so every function returns a new map. map.key syntax works for atom keys; map["key"] for string keys.

Common pipe patterns in Phoenix

# Changeset pipeline (Ecto)
%Struct{}
|> Schema.changeset(attrs)
|> Repo.insert()

# Conn pipeline (controllers/plugs)
conn
|> put_session(:user_id, user.id)
|> put_flash(:info, "Welcome!")
|> redirect(to: ~p"/dashboard")

# Socket pipeline (LiveView)
socket
|> assign(key: value)
|> assign(other: value2)

# Query pipeline (Ecto)
from(u in User, where: u.active == true)
|> order_by([u], desc: u.inserted_at)
|> Repo.all()