Qx.Result (qx v0.2.0)

View Source

Helpers 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

t()

@type t() :: t(term(), term())

t(value, reason)

@type t(value, reason) :: {:ok, value} | {:error, reason}

Functions

and_then(error, fun)

@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}

collect(results)

@spec collect([t(value, reason)]) :: t([value], reason)
when value: term(), reason: term()

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, []}

error(reason)

@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}

map(error, fun)

@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}

ok(value)

@spec ok(value) :: {:ok, value} when value: term()

Wraps a value in an :ok tuple.

Examples

iex> Qx.Result.ok(1)
{:ok, 1}

unwrap(arg, default)

@spec unwrap(t(value, term()), value) :: value when value: term()

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