Making list from range fails: Enum.to_list(27..77//5)

Ran into a ranges that refuse to turn into a list. For example the one in line 2.

iex(1)> Enum.to_list(27..77//4)
[27, 31, 35, 39, 43, 47, 51, 55, 59, 63, 67, 71, 75]

iex(2)> Enum.to_list(27..77//5)
'\e %*/49>CHM'

Line 1 gives expected list. Line 2 puzzles me.

Any explanations you can think of? Thank you.

It’s a special type of list called a charlist, a list of integers where all the integers are valid code points. The default inspect behavior is to represent such a list as the more “human readable” charlist. You can use the charlists: false option to inspect it as a list of integers.

iex(5)> '\e %*/49>CHM' |> IO.inspect(charlists: false) 
[27, 32, 37, 42, 47, 52, 57, 62, 67, 72, 77]

You can configure the shell to do this by default globally or for certain projects.

More reading:

https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html

5 Likes

Thank you. I have some reading to do, I see. :nerd_face:

1 Like

This issue comes up every other week or so on elixir forum, don’t worry. Probably the only way it goes away is if in a future version of elixir they get rid of list-encoding Erlang strings with single quotes, but that’s unlikely to happen unless Erlang makes a massive push to deprecate charlist first.

2 Likes