tschnibo

tschnibo

Enum.chunk_while/4 - am I using it right and if, is this an interesting example for the elixir documentation?

Hey fellow Elixir people,

I am still a Elixir noob and on some problems I spend a lot of time.

In order to nest a flat list into elixir structs / maps (e.g. from csv or relational db) i wrote a small parser.

The most time spent was on not understanding Enum.chunk_while/4. So as a check if I use it correctly now I wrote this small example (in form of a test). See below.

Just ahead my question: Is there a more elixir way to do that (keep in mind that I convolute multiple such chunkers and use a dynamic schema to chunk into, I guess filtering or grouping alone would not do…)?

In case this would be totally ok as a principle: What do you think, would this example (modified maybe) be something to extend the Elixir documentation? And in case there is another “Yes” here. How would that work, just a pull request to the elixir repo? The specific part which took so much time is annotated specificly below.

Many thanks for your time and consideration!

defmodule Example_chunk_while do
  @moduledoc """
  Proposition for additional Example in
  Documentation for `Enum.chunk_while`.
  """

  use ExUnit.Case

  test "chunker_test" do
    list_of_maps = [
      %{a: 5, b: 9},
      %{a: 5, b: 9},
      %{a: 7, b: 15},
      %{a: 360, b: 15},
      %{a: 360, b: 15}
    ]

    expected_result = [
      [%{a: 5, b: 9}, %{a: 5, b: 9}],
      [%{a: 7, b: 15}],
      [%{a: 360, b: 15}, %{a: 360, b: 15}]
    ]

    chunk_fun = fn element, acc ->
      # check *initial* case
      if acc == [] do
        {:cont, [element]}
      else
        # If not empty: compare with last element
        [previous | _] = acc

        previous_code = Map.get(previous, :a)

        case element.a do
          ^previous_code -> {:cont, Enum.reverse([element | acc])}
          # the following line did cost me some time to figure out!
          # In case you want to group by some features but also allow
          # entries which result in a group of "one entry", you need
          # to return the element as the acc for the next processing step.
          _ -> {:cont, acc, [element]}
        end
      end
    end

    after_fun = fn
      [] -> {:cont, []}
      acc -> {:cont, Enum.reverse(acc), []}
    end

    result = Enum.chunk_while(list_of_maps, [], chunk_fun, after_fun)

    assert result == expected_result
  end
end

Ps. I could maybe “opensource” my “parser” but it is quite messy still and changes hourly :wink:
I guess you guys already have your libraries for such things (which I didn’t really find to be honest). I am glad for pointers! I don’t currently use ecto, and I am trying to build a completely db agnostic app to begin with and add a persistency layer later on. The parser is going to be used on file.streams (with Stream.chunk_while) and on “complete” smaller files and results from outgoing db requests. Then the data is send further down the “pipeline” and gets added to the state eventually.

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

I think the main thing you could do here to make this more idiomatic is to use more pattern matching in your chunk_fun. The first step is to extract your if into a match in the function head:

chunk_fun = fn
  element, [] ->
    {:cont, [element]}

  element, [previous | _] = acc ->
    previous_code = Map.get(previous, :a)

    case element.a do
      ^previous_code -> {:cont, Enum.reverse([element | acc])}
      # the following line did cost me some time to figure out!
      # In case you want to group by some features but also allow
      # entries which result in a group of "one entry", you need
      # to return the element as the acc for the next processing step.
      _ -> {:cont, acc, [element]}
    end
end

From there, it’s somewhat personal taste but you can also extract the comparison to the function head to resulting in:

chunk_fun = fn
  element, [] ->
    {:cont, [element]}

  %{a: a} = element, [%{a: a} | _] = acc ->
    {:cont, Enum.reverse([element | acc])}

  element, acc ->
    {:cont, acc, [element]}
  end
end

What I like about this is that it highlights that there are really 3 outcomes. You’re either initializing things, you’re comparing an inner attribute for equality, or you’re passing things along. Depending on the complexity of your comparison, you may not be able to do the quality check in the function head, but it’s usually good to pull out stuff like [prev | _] = acc at least.

As a tiny point, I’m not sure that the Enum.reverse is correct, it seems to me like that would be constantly flip flopping the accumulator. Rather it seems more like you’d want:

chunk_fun = fn
  element, [] ->
    {:cont, [element]}

  %{a: a} = element, [%{a: a} | _] = acc ->
    {:cont, [element | acc]}

  element, acc ->
    {:cont, Enum.reverse(acc), [element]}
  end
end

Here, you build up the acc back to front as usual, and then reverse when you emit it as a chunk.

PRs to the Elixir repo for docs are always welcome, just as always be willing to iterate with the repo owners about wording and clarity.

al2o3cr

al2o3cr

I think you may have oversimplified the example, because it can be spelled Enum.chunk_by/2:

iex(1)>     list_of_maps = [
...(1)>       %{a: 5, b: 9},
...(1)>       %{a: 5, b: 9},
...(1)>       %{a: 7, b: 15},
...(1)>       %{a: 360, b: 15},
...(1)>       %{a: 360, b: 15}
...(1)>     ]
[
  %{a: 5, b: 9},
  %{a: 5, b: 9},
  %{a: 7, b: 15},
  %{a: 360, b: 15},
  %{a: 360, b: 15}
]

iex(2)> Enum.chunk_by(list_of_maps, & &1.a)
[
  [%{a: 5, b: 9}, %{a: 5, b: 9}],
  [%{a: 7, b: 15}], 
  [%{a: 360, b: 15}, %{a: 360, b: 15}]
]

The implementation from Stream.Reducers looks familiar:

https://github.com/elixir-lang/elixir/blob/308255bda81e7f76f9bec838cef033e8e869981b/lib/elixir/lib/stream/reducers.ex#L38-L56

al2o3cr

al2o3cr

The source for Enum and Stream are a really good read if you’re getting used to Elixir idioms, though some of them (:eyes: Stream.zip for instance) can be very challenging to follow :slight_smile:

Where Next?

Popular in Questions Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
chrismccord
This release brings a number of exciting features, including integration with the new Phoenix LiveDashboard and Phoenix LiveView. There h...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

We're in Beta

About us Mission Statement