benhoven

benhoven

Use case for Enum.reduce_while without accumulator

Hi Everybody,

Recently I discovered interesting use case for reduce_while that does not use acc as accumulator -> it doesn’t carry / use the variable in subsequent loops.

Could you please take a look and tell me if it’s clever or stupid?

Enum.reduce_while(some_enumerable, {:error, :show_this_when_empty_input}, fn some_item, _ ->
  with {:ok, something} <- something(some_item),
       {:ok, something} <- something_else(something) do
    {:halt, {:ok, something}}
  else
    # known error - continue OR finish with this error
    {:error, :expected_message} = error -> {:cont, error}

    # unknown error - halt immediately
    {:error, _} = error -> {:halt, error}
  end
end)

What I can get from that is:

  1. {:error, :show_this_when_empty_input} when enumerable is an empty list
  2. {:error, :expected_message} when no element in enumerable passes the test (the function) in 3rd argument
  3. {:ok, result} first positive result from the function -> first element that passes and then stop processing
  4. {:error, anything} for results / errors that are not expected

Marked As Solved

Eiji

Eiji

Sorry, I did not get it. Since we accept any function and expect not nil all mentioned clauses could be changed to return “something” like {:error, error} or {:ok, result} and optionally for {:error, :expected_message} we may want to return nil in order to skip specific item.

If you want you can also write a really simple few-lines function like:


defmodule Example do
  def sample(list, default \\ nil, func)

  def sample([], default, _func), do: func

  def sample([head | tail], default \\ nil, func) do
    case func.(head) do
      {:ok, something} -> something
      {:error, :expected_message} = error -> sample(tail, error, func)
      {:error, _} = error -> error
    end
  end
end

and use it like:

Example.sample(some_enumerable, {:error, :show_this_when_empty_input}, fn some_item, _ ->
  with {:ok, something} <- something(some_item),
       {:ok, something} <- something_else(something) do
    {:ok, something}
  else
    {:error, _} = error -> error
  end
end)

Look that in case clauses you may simply add support for {:halt, acc} and {:cont, acc} if you do not want to change anonymous function from an original post. You may even combine Example.sample/3 with such anonymous function.

Also Liked

kokolegorille

kokolegorille

I would also try to move the code to Enum.find, or Enum.find_value, but the condition is more complex, and not really a truthy kind of condition.

It’s hard to capture the with, with Enum.find :slight_smile:

wolf4earth

wolf4earth

I’ve written code similar to this, so yeah, I think that’s a perfectly reasonable usage of Enum.reduce_while. :slight_smile:

Eiji

Eiji

Your code looks good except one point. Calling Enum.reduce* functions does not makes sense if you do not need an accumulator. I would rather write something like:

func = fn
  # return error if needed - equivalent of: {:halt, {:error, error}}
  x when rem(x, 2) != 0 -> {:error, 2}
  # skip item if needed - equivalent of: {:cont, acc}
  x when rem(x, 3) != 0 -> nil
  # return ok tuple for desired item - equivalent of: {:halt, {:ok, item}}
  x -> {:ok, x}
end

iex> Enum.find_value(1..3, func)
{:error, 2} # error returned
iex> Enum.find_value([2, 4], func)
nil # all skipped
iex> Enum.find_value([2, 4, 6], func)
{:ok, 6} # ok returned

For more information please take a look at Enum.find_value/2 documentation.

kokolegorille

kokolegorille

I know recursion could solve this problem quite elegantly.

What I meant is Enum.find_value is not working well in that case.

Because the condition should exit only if ok, or unexpected error… and continue if the error is known. But You need to return nil/or false instead, to continue iteration :slight_smile:

Where Next?

Popular in Questions Top

lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Codball
Mix format works fine if run from the cmd. I’ve followed this to facilitate the implementation into VSC which involves downloading an ext...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
lanycrost
Hi everyone! I need implement if…else if…else condition from my elixir code, and anymore of this control flow structures not work proper...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs &amp; Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
grych
Hi folks, Few months ago I have announced the proof-of-concept of the library to manipulate the browsers DOM objects directly from Elixi...
639 49522 488
New
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New

We're in Beta

About us Mission Statement