View Source EnumX (CommonX v0.5.9)

Some enumeration extensions.

Link to this section Summary

Functions

Invokes the given fun for each item in the enumerable. Returns :ok if all calls return :ok, returns {:error, term} if any fail.

Returns a list where each item is the result of invoking fun on each corresponding item of enumerable. For maps, the function expects a key-value tuple.

Reduces the enumerable until fun returns {:error, reason}.

Link to this section Functions

@spec each(Enum.t(), (Enum.element() -> :ok | {:error, term()})) ::
  :ok | {:error, term()}

Invokes the given fun for each item in the enumerable. Returns :ok if all calls return :ok, returns {:error, term} if any fail.

examples

Examples

iex> EnumX.each([1, 2, 3], fn x -> IO.puts(to_string(x)) end)
#=> "1"
#=> "2"
#=> "3"
:ok

Will halt on first error:

iex> EnumX.each([1, 2, 3], fn x -> if x != 2, do: IO.puts(to_string(x)), else: {:error, :is_two} end)
#=> "1"
{:error, :is_two}
@spec map(Enum.t(), (Enum.element() -> {:ok, any()} | {:error, any()})) ::
  {:ok, list()} | {:error, any()}

Returns a list where each item is the result of invoking fun on each corresponding item of enumerable. For maps, the function expects a key-value tuple.

examples

Examples

iex> EnumX.map([1, 2, 3], fn x -> {:ok, x * 2} end)
{:ok, [2, 4, 6]}
iex> EnumX.map([a: 1, b: 2], fn {k, v} -> {:ok, {k, -v}} end)
{:ok, [a: -1, b: -2]}
Link to this function

reduce_while(enumerable, acc, fun)

View Source
@spec reduce_while(
  Enum.t(),
  any(),
  (Enum.element(), any() -> {:ok, any()} | {:error, any()})
) :: {:ok, any()} | {:error, any()}

Reduces the enumerable until fun returns {:error, reason}.

The return value for fun is expected to be

  • {:ok, acc} to continue the reduction with acc as the new accumulator or
  • {:error, acc} to halt the reduction and return acc as the return value of this function

examples

Examples

iex> EnumX.reduce_while(1..100, 0, fn x, acc ->
...>   if x < 3, do: {:ok, acc + x}, else: {:error, acc}
...> end)
{:error, 3}