TExcelTAD
Home › Elixir › Elixir The with Expression

Elixir The with Expression

Real programs chain operations that can each fail: parse the input, look up the user, check the balance, save the transfer. With case alone, every step nests one level deeper. The with expression flattens such a chain: it runs each step while the result matches the expected pattern, and stops at the first one that doesn't.

The problem: nested case

elixir · try it yourself
parse_age = fn input ->
  case Integer.parse(input) do
    {age, ""} ->
      case age >= 0 and age < 150 do
        true -> {:ok, age}
        false -> {:error, :out_of_range}
      end

    _ ->
      {:error, :not_a_number}
  end
end

IO.inspect(parse_age.("42"))
IO.inspect(parse_age.("-5"))
IO.inspect(parse_age.("forty"))
{:ok, 42}
{:error, :out_of_range}
{:error, :not_a_number}

The same with with

Each pattern <- expression clause must match for with to continue. If all match, the do block runs. If one doesn't match, with returns the non-matching value right away:

elixir · try it yourself
defmodule Signup do
  def parse_age(input) do
    with {age, ""} <- Integer.parse(input),
         true <- age >= 0 and age < 150 do
      {:ok, age}
    else
      :error -> {:error, :not_a_number}
      {_age, _rest} -> {:error, :not_a_number}
      false -> {:error, :out_of_range}
    end
  end
end

IO.inspect(Signup.parse_age("42"))
IO.inspect(Signup.parse_age("-5"))
IO.inspect(Signup.parse_age("forty"))
IO.inspect(Signup.parse_age("42abc"))
{:ok, 42}
{:error, :out_of_range}
{:error, :not_a_number}
{:error, :not_a_number}

The optional else block works like a case on the value that failed to match. Without else, that value is returned as is.

Chaining {:ok, _} functions

with is at its best when every step returns {:ok, value} or {:error, reason}. Then you usually don't need an else at all, because the error tuple passes straight through:

elixir · try it yourself
defmodule Bank do
  @accounts %{"alice" => 120, "bob" => 15}

  def fetch_account(name) do
    case Map.fetch(@accounts, name) do
      {:ok, balance} -> {:ok, balance}
      :error -> {:error, {:unknown_account, name}}
    end
  end

  def check_funds(balance, amount) when balance >= amount, do: {:ok, balance - amount}
  def check_funds(_balance, _amount), do: {:error, :insufficient_funds}

  def withdraw(name, amount) do
    with {:ok, balance} <- fetch_account(name),
         {:ok, new_balance} <- check_funds(balance, amount) do
      {:ok, "#{name} now has #{new_balance}"}
    end
  end
end

IO.inspect(Bank.withdraw("alice", 50))
IO.inspect(Bank.withdraw("bob", 50))
IO.inspect(Bank.withdraw("carol", 5))
{:ok, "alice now has 70"}
{:error, :insufficient_funds}
{:error, {:unknown_account, "carol"}}

@accounts is a module attribute used as a constant (see the Module Attributes lesson).

Plain matches and guards inside with

Besides <- clauses, with accepts ordinary = matches (which raise if they fail, like any match) and guards on the <- clauses:

elixir · try it yourself
order = %{items: [%{price: 10, qty: 2}, %{price: 4, qty: 5}], coupon: "SAVE10"}

result =
  with %{items: items} when items != [] <- order,
       subtotal = Enum.sum(Enum.map(items, &(&1.price * &1.qty))),
       {:ok, pct} <- (if order.coupon == "SAVE10", do: {:ok, 10}, else: {:ok, 0}) do
    subtotal - div(subtotal * pct, 100)
  end

IO.inspect(result)

empty = with %{items: items} when items != [] <- %{items: []}, do: :has_items
IO.inspect(empty)
36
%{items: []}

The with for empty fails at its first clause because of the guard, so it returns the unmatched value %{items: []}.

Tips

  • Keep each step a small function that returns tagged tuples. with then reads like a list of steps.
  • Avoid big else blocks that try to guess which step failed. If errors need different handling, make each step return a distinct error ({:error, :not_found}, {:error, :insufficient_funds}).
  • with variables are only visible inside its do block.

Test yourself

What does with {:ok, x} <- {:error, :nope}, do: x return?

  1. nil
  2. {:error, :nope}
  3. It raises a MatchError
  4. :nope

When does the else block of a with run?

  1. Always, after the do block
  2. When one of the <- clauses fails to match
  3. When the do block raises
  4. Only when every clause fails

What happens if an = clause inside with fails to match?

  1. with returns the value
  2. A MatchError is raised
  3. The else block runs
  4. It is skipped