I was reading through the Enum module functions and copying them into the repl to get a feel for how they work. I pasted the following into the repl from the documentation.
Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))
Instead of it returning this, as it should per the docs:
[, [2, 2], , [4, 4, 6], [7, 7]]
It returned this:
[, [2, 2], , [4, 4, 6], '\a\a']
What’s going on?
I even got the same result when I used an online repl.
A list containing only integers that represent printable ASCII is indistinguishable from an Erlang charlist.
The REPL uses
inspect which tries to pick the correct representation based on the values in the list: if none of them are unprintable, they are displayed as a charlist - because
'hello' is more readable than a list of numbers:
iex(2)> inspect('hello', charlists: false)
"[104, 101, 108, 108, 111]"
As @al2o3cr mentioned, you should check a :charlist option from the Inspect.Opts — Elixir v1.12.3
iex> inspect([7,7], charlists: :as_list)
Is there a global
charlists option in
iex? I almost never really want
iex to display a
charlist instead of a list of ints, so I would much rather have to opt into displaying as charlist.
You can set it globally using The .iex.exs file by adding the following:
# Show charlists as a List
IEx.configure(inspect: [charlists: :as_lists])
The repl is trying to “inspect” the return value and it can’t distinguish between a list of integers or a “charlist”.
You can force it to interpret as a list of integers, but I forgot how.
You can also do this:
list = Enum.chunk_by([1, 2, 2, 3, 4, 4, 6, 7, 7], &(rem(&1, 2) == 1))
inspect(list, charlists: :as_lists)
A charlist is a list of characters, i.e. like this:
['a', 'b', 'c'] and a char is basically an integer, so the repl gets confused with how to display a list of ints.
Gah, I forgot to hit the reply button and several people have already answered, but I’m going to hit the button anyway so I can feel smart and good about myself…