Qx.Result (qx v0.2.0)
View SourceHelpers for working with the {:ok, value} / {:error, reason} tuples that
Elixir uses everywhere, so a chain of fallible calls reads as a pipeline
instead of a nest of case expressions.
Summary
Functions
Chains another result-returning call onto an :ok tuple, short-circuiting on
the first error.
Turns a list of results into a result of a list, stopping at the first error.
Wraps a reason in an :error tuple.
Applies fun to the value of an :ok tuple, leaving errors untouched.
Wraps a value in an :ok tuple.
Returns the wrapped value, or default when the result is an error.
Types
Functions
@spec and_then(t(value, reason), (value -> t(new, reason))) :: t(new, reason) when value: term(), new: term(), reason: term()
Chains another result-returning call onto an :ok tuple, short-circuiting on
the first error.
Examples
iex> Qx.Result.and_then({:ok, 4}, fn n -> {:ok, n + 1} end)
{:ok, 5}
iex> Qx.Result.and_then({:ok, 0}, fn 0 -> {:error, :zero} end)
{:error, :zero}
iex> Qx.Result.and_then({:error, :nope}, fn n -> {:ok, n + 1} end)
{:error, :nope}
Turns a list of results into a result of a list, stopping at the first error.
Examples
iex> Qx.Result.collect([{:ok, 1}, {:ok, 2}])
{:ok, [1, 2]}
iex> Qx.Result.collect([{:ok, 1}, {:error, :nope}, {:error, :also_nope}])
{:error, :nope}
iex> Qx.Result.collect([])
{:ok, []}
@spec error(reason) :: {:error, reason} when reason: term()
Wraps a reason in an :error tuple.
Examples
iex> Qx.Result.error(:not_found)
{:error, :not_found}
@spec map(t(value, reason), (value -> new)) :: t(new, reason) when value: term(), new: term(), reason: term()
Applies fun to the value of an :ok tuple, leaving errors untouched.
Examples
iex> Qx.Result.map({:ok, 2}, &(&1 * 10))
{:ok, 20}
iex> Qx.Result.map({:error, :nope}, &(&1 * 10))
{:error, :nope}
@spec ok(value) :: {:ok, value} when value: term()
Wraps a value in an :ok tuple.
Examples
iex> Qx.Result.ok(1)
{:ok, 1}
Returns the wrapped value, or default when the result is an error.
Examples
iex> Qx.Result.unwrap({:ok, 1}, 0)
1
iex> Qx.Result.unwrap({:error, :nope}, 0)
0