Why does `inspect [i]` behavior vary for certain values below 128 and how can I prevent it?

I’m on Elixir 1.12.3 (compiled with Erlang/OTP 24).
I’m running into interesting behaviors that stem from [int] being interpreted differently for certain low values.
For example, while [5] gets inspected as [5], [6] becomes ‘\a’.
Is there a way to force Elixir to interpret [int] as an array of a single int?

Full code:

for i <- 0..40, do: inspect [i]
["[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "'\\a'", "'\\b'", "'\\t'",
 "'\\n'", "'\\v'", "'\\f'", "'\\r'", "[14]", "[15]", "[16]", "[17]", "[18]",
 "[19]", "[20]", "[21]", "[22]", "[23]", "[24]", "[25]", "[26]", "'\\e'",
 "[28]", "[29]", "[30]", "[31]", "' '", "'!'", "'\"'", "'#'", "'$'", "'%'",
 "'&'", "'\\''", "'('"]

I’d appreciate any pointers. Thanks!

Hi :wave: and welcome to the forum!

What you have encountered is a charlist. All that has changed is the representation of the data [7] == '\a', they’re just two different ways to write the same value. There’s some more info in the Elixir common gotchas page: My list of integers is printing as a string

7 Likes

if inspect/2 encounters a list of integers that are all printable, it encodes it as charlist. If you want to encode it as integer list in such cases instead, use the charlists option, e.g
inspect([97, 98, 99], charlists: :as_lists). Without the option it would be encoded as ‘abc’, with the opt - as [97, 98, 99].

5 Likes

Thanks both! I realized I was printing chars, but not how to avoid the default inspect behavior.
I’m working in a LiveBook and printing, let’s say, \r breaks the layout in unexpected ways.
With Inspect.Opts and charlists: :as_lists, inspect now works in a safe way:

for i <- 0..40, do: inspect([i], charlists: :as_lists)
["[0]", "[1]", "[2]", "[3]", "[4]", "[5]", "[6]", "[7]", "[8]", "[9]", "[10]",
 "[11]", "[12]", "[13]", "[14]", "[15]", "[16]", "[17]", "[18]", "[19]", "[20]",
 "[21]", "[22]", "[23]", "[24]", "[25]", "[26]", "[27]", "[28]", "[29]", "[30]",
 "[31]", "[32]", "[33]", "[34]", "[35]", "[36]", "[37]", "[38]", "[39]", "[40]"]
1 Like