Skip to content

Instantly share code, notes, and snippets.

@h4cc
Created June 12, 2017 06:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h4cc/63cdf7a9876395d436982d2decd2155b to your computer and use it in GitHub Desktop.
Save h4cc/63cdf7a9876395d436982d2decd2155b to your computer and use it in GitHub Desktop.
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}
end
end
# 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]}
end
end
end
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