CommonX v0.5.2 EnumX View Source
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
each(enumerable, fun)
View Sourceeach(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
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}
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
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]}
Reduces the enumerable until fun
returns {:error, reason}
.
The return value for fun
is expected to be
{:ok, acc}
to continue the reduction withacc
as the new accumulator or{:error, acc}
to halt the reduction and returnacc
as the return value of this function
Examples
iex> EnumX.reduce_while(1..100, 0, fn x, acc ->
...> if x < 3, do: {:ok, acc + x}, else: {:error, acc}
...> end)
{:error, 3}