Why does IO.inspect print escape characters?

Hello

I have a newbie question. Why does IO.inspect give the following result?

IO.inspect [[6,9], [7,9], [8,9], [9,9]]

Output:
[[6, 9], ‘\a\t’, ‘\b\t’, ‘\t\t’]

What is up with the escape characters?

1 Like

Anytime you are curious about something like that, put i in front of it in the shell:

iex(1)> i '7,9'
Term
  '7,9'
Data type
  List
Description
  This is a list of integers that is printed as a sequence of characters
  delimited by single quotes because all the integers in it represent valid
  ASCII characters. Conventionally, such lists of integers are referred to
  as "charlists" (more precisely, a charlist is a list of Unicode codepoints,
  and ASCII is a subset of Unicode).
Raw representation
  [55, 44, 57]
Reference modules
  List
Implemented protocols
  IEx.Info, Collectable, Enumerable, Inspect, List.Chars, String.Chars

I.E. a list of integers is a charlist. :slight_smile:

2 Likes

Thank you for a quick reply! :slight_smile:

General Elixir Newbie Advice: Always use double quotes when you use strings! You only use single quotes basically when interfacing with erlang code which uses charlists for its string representation system.

But why is the first list “list of numbers” [6,9] not escaped, and the rest are? I find this very odd…

If integer is “non ASCII”, it will be shown as it is. Otherwise, the character, that is under this number in ASCII table. Check this answer on SO.

6 Likes

Thank you

Bumping this excellent Noob question.

This is something confuses many new to Elixir. The Inspect protocol for lists (which is what displays something in iex, defaults to a charlist if all the elements of the list are printable characters, including printable control characters like \t \r \n, etc.

If you are working in iex, this can be a pain if you’re looking at an integer list that just happens to have all printable characters. If you have this issue in iex, try using i on the list, or add a non printing integer to the list as shown below.

iex(1)> 'test'
'test'

iex(11)> 'test' ++ [0]
[116, 101, 115, 116, 0]

iex(8)> [9, 13, 48, 50]
'\t\r02'

iex(9)> i '\t\r02'
Term
  '\t\r02'
Data type
  List
Description
  This is a list of integers that is printed as a sequence of characters
  delimited by single quotes because all the integers in it represent valid
  ASCII characters. Conventionally, such lists of integers are referred to as
  "charlists" (more precisely, a charlist is a list of Unicode codepoints,
  and ASCII is a subset of Unicode).
Raw representation
  [9, 13, 48, 50]
Reference modules
  List
Implemented protocols
  IEx.Info, Inspect, String.Chars, List.Chars, Collectable, Enumerable

iex(10)> [0, 9, 13, 48, 50]
[0, 9, 13, 48, 50]

iex(13)> '\t\r02' == [9, 13, 48, 50]
true
4 Likes

Thanks :slight_smile:

1 Like