Question on List &tail/1 function

In the example below, why tail is not returning the tail value of the last element.

iex(28)> Enum.map([[1,2,3],[4,5,6],[7,8,9]], &hd/1)
[1, 4, 7]  # as expected
iex(29)> Enum.map([[1,2,3],[4,5,6],[7,8,9]], &tl/1)
[[2, 3], [5, 6], '\b\t']  # I was expecting: => [[2, 3], [5, 6], [8,9]]

:wave:

And you got what you expected, but it was presented as a charlist.

iex(1)> [8, 9]
'\b\t'
4 Likes

ah! thanks for pointing out that. But why is this inconsistency ? Isn’t it more logical either return everything as numbers or everything as charlist ?

Lists with integers are printed as charlists if they can be represented as charlists, and they are printed as numbers if they cannot be represented as charlists.

3 Likes

perfect! thanks for clarifying:

iex(18)> IO.inspect Enum.map([[7,8,9],[1,2,3],[4,5,6]], &tl/1), charlists: :as_lists
[[8, 9], [2, 3], [5, 6]]
['\b\t', [2, 3], [5, 6]]
iex(19)>

You can also use i Enum.map([[7,8,9],[1,2,3],[4,5,6]], &tl/1). This will give you more details about the data you passed to i/1.

3 Likes