Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Elixir example for using "with" for a "unhappy path" lol.
# Checkout: WithExample.inverse_with
defmodule WithExample do
# Helper functions
def ok(result), do: {:ok, result}
def error(error), do: {:error, error}
# This is what we all have in mind and see in the examples.
# Following a "happy path" and break if we leave that path.
def normal_with do
with {:ok, a} <- ok(1),
{:ok, b} <- ok(2),
{:ok, c} <- ok(3) do
{:ok, a+b+c}
# But what if we _want_ to find the first "break of the happy path"?
# We simply need to inverse the "happy path" to a "unhappy path".
def inverse_with do
with {:error, a} <- error(:a),
{:error, b} <- ok(42),
{:error, c} <- error(:c) do
{:error, [a, b, c]}
IO.inspect(WithExample.normal_with) # {:ok, 6}
IO.inspect(WithExample.inverse_with) # {:ok 42}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.