Does Enum.chunk_by have a bug?

Hi!
I am new in Elixir. Still learning syntax. But I I see very weird behavior while I am testing functions.

The question is about Enum.chunk_by function.

list=[1,2,3,4,5,6,7,8,9,10]
Enum.chunk_by(list, & rem(&1,4)==0)

expected result is,

[[1,2,3],[4],[5,6,7],[8],[9,10]]

but, what I am receiving is

[[1, 2, 3], [4], [5, 6, 7], ~c"\b", ~c"\t\n"]

My elixir version is 1.17.3, on MacOS 15.1.1, M1 Pro

I am curious if there is some system-relative background of this result.
Thank you!

===

Answer for this question:
turned out ~c"\b" is equivalent to [8], and ~c"\t\n" is equivalent to [9,10]
as the chosen answer explains. This looks like a common mistake that a beginner is confused (like me). Thanks for all the answers! I couldn’t understand the short answers, but after I understand what is happening, even the short answers makes sense.

The ~c sigil indicates a charlist

https://hexdocs.pm/elixir/binaries-strings-and-charlists.html#charlists

Hey, @al2o3cr , thanks for taking a look.
My question is if the result is expected, if so, why?
As I see the document, it says it should create chunk when callback function returns different value.
the callback function & rem(&1,4)==0 will return like this:
[false, false, false, true, false, false, false, true, false, false]
because rem(1,4)==1, rem(2,4)==2, rem(3,4)==3, rem(4,4)==0,…
so, rem(&1,4) will be [1,2,3,0,1,2,3,0,1,2]

But, why ~c"\b" and ~c"\t\n" comes to where [8], [9,10] should be?

Check out this post and read the rest of its thread as well:

1 Like

Short answer:

“This is done to ease interoperability with Erlang, even though it may lead to some surprising behavior. For example, if you are storing a list of integers that happen to range between 0 and 127, by default IEx will interpret this as a charlist and it will display the corresponding ASCII characters.”

https://hexdocs.pm/elixir/main/binaries-strings-and-charlists.html

2 Likes