Skip to content

Instantly share code, notes, and snippets.

@shahryarjb
Created August 4, 2017 07:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahryarjb/ada09507177541ff182d7aded9a24d07 to your computer and use it in GitHub Desktop.
Save shahryarjb/ada09507177541ff182d7aded9a24d07 to your computer and use it in GitHub Desktop.
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