Quotidien Shaarli

Tous les liens d'un jour sur une page.

May 15, 2026

Event Sourcing with Elixir · Allan MacGregor
thumbnail

Event Sourcing with Elixir

today I Learned: Elixir's then/2 for awkward pipe positions

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:

  1. Start with a string.
  2. :crypto.hash/2 has signature (algorithm, data) — the data goes second, so we need then to slot our piped value into &1.
  3. Hex-encode the resulting binary.
  4. 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.