pertsevds

pertsevds

Different behavior between List.flatten() and Enum/Stream.flat_map()

When i use List.flatten() it would flatten a deep list with every nested .

iex> list = [[],["ant",["hello","hi",[[[]]]], "bat"], ["cat", "dog"]]
[[], ["ant", ["hello", "hi", [[[]]]], "bat"], ["cat", "dog"]]
iex> List.flatten(list)
["ant", "hello", "hi", "bat", "cat", "dog"]

As expected.

But when i do Stream.flat_map()

iex(6)> list = [[],["ant",["hello","hi",[[[]]]], "bat"], ["cat", "dog"]]
[[], ["ant", ["hello", "hi", [[[]]]], "bat"], ["cat", "dog"]]
iex(7)> list
[[], ["ant", ["hello", "hi", [[[]]]], "bat"], ["cat", "dog"]]
iex(8)> |> Stream.flat_map(& &1)
#Function<60.124013645/2 in Stream.transform/3>
iex(9)> |> Enum.to_list()
["ant", ["hello", "hi", [[[]]]], "bat", "cat", "dog"]

It flattens only the first level of the list. It’s a flatten() with depth == 1.

And that was not what i expected.
I needed a deep_flatten() for Stream, so i’ve made it like this:

defmodule ExTelnet.StreamDeepFlatten do
  def deep_flatten(enumerables) do
    deep_flat_map(enumerables, & &1)
  end

  def deep_flatten(first, second) do
    deep_flat_map([first, second], & &1)
  end

  def deep_flat_map(enum, mapper) when is_function(mapper, 1) do
    Stream.transform(enum, nil, fn val, nil ->
      case val do
        val when is_list(val) -> {deep_flat_map(val, mapper), nil}
        val -> {[mapper.(val)], nil}
      end
    end)
  end
end

Works as expected for me:

iex(2)> list = [[],["ant",["hello","hi",[[[]]]], "bat"], ["cat", "dog"]]
iex(3)> list
iex(4)> |> Stream.map(&IO.inspect(&1))
iex(5)> |> ExTelnet.StreamDeepFlatten.deep_flatten()
iex(6)> |> Stream.map(&IO.inspect(&1))
iex(7)> |> Stream.map(&("seen " <> &1))
iex(8)> |> Stream.map(&IO.inspect(&1))
iex(9)> |> Enum.to_list()
[]
["ant", ["hello", "hi", [[[]]]], "bat"]
"ant"
"seen ant"
"hello"
"seen hello"
"hi"
"seen hi"
"bat"
"seen bat"
["cat", "dog"]
"cat"
"seen cat"
"dog"
"seen dog"
["seen ant", "seen hello", "seen hi", "seen bat", "seen cat", "seen dog"]

So what i’m questioning myself now is: “Am I reinvening the wheel? Maybe there is some better simpler method and I just don’t see it?”

Most Liked

josevalim

josevalim

Creator of Elixir

Hi everyone, I believe @davaeron understands the differences between them. The question is about naming.

Correct. This is common nomenclature in all functional languages. Also add Scala and Erlang to your list.

You should read it as a “flat map operation”, i.e. as a map operation that joins its consecutive results, not as a “map plus flatten”.

Sebb

Sebb

behaves like Enum.flat_map/2 not like List.flatten/1

lucaong

lucaong

One reason: flat_map flattening a single level, and flatten flattening multiple levels, produces a more versatile behavior: if one needs to flatten only a single level (maybe the nested items are collections themselves and should be treated as individual items) one can use flat_map. If multiple levels should be flattened, one can call flatten inside the function called by flat_map.

Last Post!

pertsevds

pertsevds

Thank you. Now it is clear.

Where Next?

Popular in Discussions Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54921 245
New
AstonJ
I’ve just started the Phoenix part of the utterly brilliant online course by @pragdave. On generating the Phoenix app he uses the --no-ec...
New
chulkilee
Here are the list of HTTP client libraries/wrappers, and some thoughts on HTTP client in general. I’d like to hear from others how they w...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 40042 209
New
eteeselink
Hi all, In the last days, two things happened: A blog post titled “They might never tell you it’s broken” made the rounds. It’s about ...
New
RudManusachi
What configs will make sense to put to runtime.exs? – A bit of how I configure apps: I have generic configs in config/config.exs, dev...
New
AstonJ
Can you believe the first professionally published Elixir book was published just 8 years ago? Since then I think we’ve seen more books f...
New

Other popular topics Top

nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1144 54921 245
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
joeerl
Hello again - after a longish gap I’ve decided I really must dig into Elixir and see what’s been happening here - so I have a few questio...
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