Created
June 12, 2017 06:31
-
-
Save h4cc/63cdf7a9876395d436982d2decd2155b to your computer and use it in GitHub Desktop.
Elixir example for using "with" for a "unhappy path" lol.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# 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