with chains

In Elixir, a with lists the steps of a happy path one per line. Each step is a match: when it fits, the chain continues with the names it bound, and when it does not, the whole form returns that value instead of running the body. It is the flat way to write the nested case blocks that a run of fallible steps would otherwise need.

A chain of steps

The left arrow <- marks a step. Map.fetch/2 returns {:ok, value} or :error, so the pattern {:ok, name} continues only when the key was there. When every step fits, the do block runs with all the names bound:

chain.exs

user = %{name: "Ada", age: 36} result = with {:ok, name} <- Map.fetch(user, :name), {:ok, age} <- Map.fetch(user, :age) do {:ok, {name, age}} end IO.inspect(result)

elixir chain.exs

{:ok, {"Ada", 36}}

Each step sees the names bound by the steps above it, and the body sees them all. A step written with = instead of <- is a plain binding that must always fit; it cannot stop the chain, which is why a fallible call uses the arrow.

Else reroutes a failure

Without an else, a failed step is the value of the whole with. That is often enough, and it is exactly what a caller of a function that returns an error tuple expects. When the failure needs a different shape, an else block names the values it handles:

else.exs

user = %{name: "Ada"} with_else = with {:ok, name} <- Map.fetch(user, :name), {:ok, age} <- Map.fetch(user, :age) do {:ok, {name, age}} else :error -> {:error, :missing_field} end without_else = with {:ok, name} <- Map.fetch(user, :name), {:ok, age} <- Map.fetch(user, :age) do {:ok, {name, age}} end IO.inspect(with_else) IO.inspect(without_else)

elixir else.exs

{:error, :missing_field}
:error

The missing key made Map.fetch/2 return :error, the second step did not fit, and the body never ran. With the else block the caller gets the tagged error; without it the caller gets the value the step produced, which is honest but sometimes too raw for a public function.

A filter step

A step whose pattern is a plain value works as a filter. true <- n > 0 continues only when the comparison is true, and otherwise the chain stops with false as its value:

filter.exs

count = 3 IO.inspect( with {:ok, n} <- Map.fetch(%{count: count}, :count), true <- n > 0 do {:ok, n} end ) negative = -1 IO.inspect( with {:ok, n} <- Map.fetch(%{count: negative}, :count), true <- n > 0 do {:ok, n} end )

elixir filter.exs

{:ok, 3}
false

The second call shows the cost of a filter without an else: the caller gets false, not an error tuple. Add an else clause for false when the caller needs to tell a failed validation from a failed fetch. The filter is the reason a with can replace a chain of ifs as well as a chain of cases.

Flat instead of nested

The same chain with case inside case grows one level of indentation per step, and the error handling is repeated at every level. A with keeps the steps at one level and the recovery in one else. The rule of thumb: when every step must succeed before the body makes sense, use with; when the steps are independent decisions, use case or cond.

The mistake: else misses a shape

An else block is a case over the failed value, and it must cover every shape the steps can produce. A block that names only {:error, reason} does not cover :error, and the program stops with a WithClauseError:

uncovered.exs

user = %{name: "Ada"} with {:ok, name} <- Map.fetch(user, :name), {:ok, age} <- Map.fetch(user, :age) do {name, age} else {:error, reason} -> reason end

elixir uncovered.exs

** (WithClauseError) no with clause matching:

    :error

    uncovered.exs:3: anonymous fn/1 in :elixir_compiler_0.__FILE__/1
    (elixir 1.19.7) lib/code.ex:1613: Code.require_file/2

The report says which value the else block could not match, and the stack follows. The fix is the missing arm, usually :error next to the tuple arm, or a catch-all that turns every failure into one shape. A with without an else cannot make this mistake, because every failed step is simply returned.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does a <- step do in a with?

    Answer

    It matches the value and stops the chain when the pattern does not fit

    The arrow marks a fallible step; a failed match makes the whole with return that value.

  2. What is the value of a with when a step fails and there is no else?

    Answer

    The value that the failed step produced

    Without else the failed value is returned as it is, which is why callers see :error.

  3. What is an else block of a with?

    Answer

    A case over the failed value, which must cover every shape it can take

    The else block matches the failure, and an uncovered shape raises WithClauseError.

  4. What does a step like true <- n > 0 do?

    Answer

    It filters: the chain continues only when the comparison is true

    The pattern true matches only true, so a false comparison stops the chain.

  5. What does this program print? IO.inspect( with {:ok, name} <- Map.fetch(%{name: "Ada", age: 36}, :name), {:ok, age} <- Map.fetch(%{name: "Ada", age: 36}, :age) do {:ok, {name, age}} end )

    Answer

    {:ok, {"Ada", 36}}

    Both keys are present, so the body runs and returns the tagged pair.

  6. What does this program print? IO.inspect( with {:ok, name} <- Map.fetch(%{name: "Ada"}, :name), {:ok, age} <- Map.fetch(%{name: "Ada"}, :age) do {:ok, {name, age}} end )

    Answer

    :error

    The age key is missing, the step returns :error, and without else the with returns it.

  7. What does this program print? IO.inspect( with {:ok, n} <- Map.fetch(%{count: -1}, :count), true <- n > 0 do {:ok, n} end )

    Answer

    false

    The comparison is false, the filter step fails, and the value of the with is false.

  8. What does this program print? IO.inspect( with {:ok, name} <- Map.fetch(%{name: "Ada"}, :name), {:ok, age} <- Map.fetch(%{name: "Ada"}, :age) do {:ok, {name, age}} else :error -> {:error, :missing_field} end )

    Answer

    {:error, :missing_field}

    The missing key produces :error, and the else block turns it into the tagged error.

  9. What does this program do? with {:ok, name} <- Map.fetch(%{name: "Ada"}, :name), {:ok, age} <- Map.fetch(%{name: "Ada"}, :age) do {name, age} else {:error, reason} -> reason end

    Answer

    A WithClauseError, because the else block has no arm for :error

    Map.fetch/2 returns :error, which matches no else arm, so the with clause fails.

  10. When does a with read better than nested case expressions?

    Answer

    When a run of steps must all succeed before the body runs

    with keeps a happy path at one level and collects the failure handling in one place.

Автор статьи: Arthur Isaev