Version Information:
Erlang/OTP 22 [erts-10.6.4]
Elixir (1.10.4)
Specific phenomena:
iex> 0..99 |> Enum.slice(6..6)
[6] # ok
iex> 0..99 |> Enum.slice(6..7)
[6, 7] # ok
iex> 0..99 |> Enum.slice(7..7)
'\a' # ???
iex> 0..99 |> Enum.slice(7..8)
'\a\b' # ???
iex> 0..99 |> Enum.slice(6..8)
[6, 7, 8] # ok
If it reaches the end of 13
, all letters are suspected to be returned. After 14
can return to the element list normally:
iex> 0..99 |> Enum.slice(7..13)
'\a\b\t\n\v\f\r'
iex> 0..99 |> Enum.slice(7..14)
[7, 8, 9, 10, 11, 12, 13, 14]
They are equivalent. Elixir simply prints a list of integers as a character list if all of the integers in the list represent printable characters.
Try this in iex
:
'\n' == [10]
You should see true
as an output, i.e. they are fully equivalent.
(Reminder: the newline character \n
is encoded with the integer 10
.)
This does not in any way change the fact that the underlying list is correct. Simply a small debug printing convenience which, judging by the amount of the same questions here in ElixirForum, turned out to be more of a tripping stone for many.
2 Likes
Thank you for your prompt answers. They are indeed equivalent.
However, this result is really elusive, making me completely forget that this is a unique phenomenon when printing.
Because I happen to be testing a bug related to Enum.slice/2
call.
If you use IO.inspect you can user :charlists option to show it as a list
https://hexdocs.pm/elixir/Inspect.Opts.html
4 Likes
Recommendation: make your own IO.inspect
wrapper with the proper options passed in. Do these in an iex
console (the h
helper prints the docs of what comes after it):
h IO.inspect
h Inspect.Opts
EDIT: To illustrate what @emoragaf is saying:
IO.inspect([7, 8], charlists: :as_lists)
Yields [7, 8]
.
1 Like