← 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 &
| Shorthand | Expands to |
& &1.name | fn x -> x.name end |
&(&1 + &2) | fn x, y -> x + y end |
&String.upcase/1 | fn x -> String.upcase(x) end |
&to_string/1 | fn x -> to_string(x) end |
Enum: most used functions
| Elixir | Ruby | Returns |
Enum.map(list, fun) | .map | list |
Enum.filter(list, fun) | .select | list |
Enum.reject(list, fun) | .reject | list |
Enum.find(list, fun) | .find / .detect | element or nil |
Enum.reduce(list, acc, fun) | .inject / .reduce | accumulator |
Enum.group_by(list, fun) | .group_by | map |
Enum.sort_by(list, fun) | .sort_by | list |
Enum.flat_map(list, fun) | .flat_map | list |
Enum.count(list) | .count / .length | integer |
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_a | collectable |
Enum.zip(list_a, list_b) | .zip | list of tuples |
Map module: key-value operations
| Function | Does |
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()