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:

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

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
pgiesin
This should be a simple problem but I just can’t seem to figure it out. I have a standalone Elixir app that won’t find the database. Dep...
New
dokuzbir
Hello, I am trying to convert my lists to string without losing brackets.For start i have 3 map. They look like these buyer = %{ id: ...
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
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
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
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
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
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> someth...
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
TunkShif
This post is an instruction guide to help you setup your Neovim for Elixir development from scratch. It includes general information on h...
273 38985 115
New

We're in Beta

About us Mission Statement