364 shaares
3 liens privés
3 liens privés
Today I learned
The pipe operator |> always passes the value as the first argument. But sometimes the function you want needs it somewhere else.
then/2 solves this by wrapping the call in an anonymous function so you can place the piped value in any slot via &1.
Example
"super-secret-token"
|> then(&:crypto.hash(:sha256, &1))
|> Base.encode16(case: :lower)
|> binary_part(0, 8)
Step by step:
- Start with a string.
:crypto.hash/2has signature (algorithm, data) — the data goes second, so we need then to slot our piped value into&1.- Hex-encode the resulting binary.
- Keep the first 8 chars as a short fingerprint.
Without then, writing "super-secret-token" |> :crypto.hash(:sha256) would expand to :crypto.hash("super-secret-token", :sha256) — arguments swapped, crash.
Think of then as an escape hatch: "pipe into this specific slot, not the default first one." Especially handy with Erlang stdlib calls (:crypto, :binary, :ets) whose signatures weren't designed pipe-first.