Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
defmodule WithTest do
def ok(x), do: {:ok, x}
def error(x), do: {:error, x}
end
IO.inspect with {:ok, x} <- WithTest.ok(1),
{:ok, y} <- WithTest.ok(2),
do: {:ok, x + y}
IO.puts "----------------------------\n"
IO.inspect with {:ok, x} <- WithTest.ok(1),
{:ok, y} <- WithTest.error(2),
do: {:ok, x + y}
defmodule WithTest1 do
def plus(x) do
if x + 1 == 2 do
{:ok,x}
end
end
def pluss(x) do
if x + 1 == 2 do
{:ok, x}
else
{:error}
end
end
def run do
with {:ok, x} <- WithTest1.plus(2),
{:ok, y} <- WithTest1.pluss(1) do
{:ok, x + y}
else
:error -> {:error, :wrong_data}
nil -> {:error, :wrong_data1}
end
end
end
IO.inspect WithTest1.run
ref
https://stackoverflow.com/questions/34210281/how-to-use-the-with-keyword-in-elixir-and-what-is-it-for
https://gist.github.com/josevalim/8130b19eb62706e1ab37
https://hexdocs.pm/elixir/master/Kernel.SpecialForms.html#with/1
https://hexdocs.pm/elixir/master/WithClauseError.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment