What's happening with this list enumeration?

Hi,

I’m just learning elixir and following the basics of Elixir School’s lessons I found something that shocked me. Please take this dumb example:

iex(33)> Enum.chunk_by([1, 2, 3, 4, 5, 6, 7], fn(x) -> rem(x, 2) == 0 end)

I expected it to return a list of one single item lists, like in [[1], [2], [3], [4], [5], [6], [7]] but instead I got

[[1], [2], [3], [4], [5], [6], '\a']

Why is the [7] shown as \a? Is this because of the 7 (codepoint?) meaning some non-printable character?

If the result lists are not single-item this doesn’t happen (I suspect because no interpretation of the value as codepoint happens):

iex(34)> Enum.chunk_by([2, 4, 6, 1, 3, 5, 7], fn(x) -> rem(x, 2) == 0 end)
[[2, 4, 6], [1, 3, 5, 7]]

Thanks in advance!

This is THE classic learning everyone who is new to elixir goes through. The answer is [7] is the same as ‘\a’

Note how the string has single quotes. That’s because it’s not a string, it is a char list, which is literally a list of codepoints. So the two are equivalent.

The shell sometimes tries to be helpful and print those numbers as a bit list but its giving the right answer.

4 Likes

Sorry i called it a bit list i meant char list you can read about it here: https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#charlists

1 Like

@Adzz is right, they are the same. Indeed, you can turn this inspecting feature off to see it in numbers:

iex> Enum.chunk_by([1, 2, 3, 4, 5, 6, 7], &(rem(&1, 2) == 0)) |> IO.inspect(charlists: false)
[[1], [2], [3], [4], [5], [6], [7]]
[[1], [2], [3], [4], [5], [6], '\a']
2 Likes