I am currently learning Elixir using Dave Thomas’s book Programming Elixir in which he states that
If all the values in a list represent printable characters, it displays the list as a string; otherwise it displays a list of integers
and am curious about the following:
a = 'r'
[head | _tail] = a
IO.puts head #This prints the binary representation of r: 114
IO.puts [head] #This print the letter r
Why does wrapping the head variable in a list change the way that it is displayed. If I instead do not split ‘a’ into a head and tail and instead print it out directly, it prints out a string always.
Head is not a list; it is a single integer.
The classic erlang
string is represented as a list of bytes. ‘r’ is in fact . This is called a charlists in elixir. (
[104, 101, 108, 108, 111]
is the same thing. The last one being the internal format.
As to why it changes the display. IO.puts will interpret a charlist as string and print it as such. If the incoming parameter is not a list it will perform a to_string conversion which is different depending on the data type. In the case of  this can be displayed as
r whereas 114 is just an integer which it will print as an integer.
iex(1)> cl = 'abc'
iex(2)> IO.inspect(cl,[charlists: :as_charlists])
iex(3)> IO.inspect(cl,[charlists: :as_list])
[97, 98, 99]
iex(6)> IO.inspect(,[charlists: :as_list])
iex(7)> IO.inspect('r',[charlists: :as_charlists])
iex(8)> IO.inspect('r',[charlists: :as_list])
:charlists - when
:as_charlists all lists will be printed as char lists, non-printable elements will be escaped.
:as_lists all lists will be printed as lists.
When the default
:infer , the list will be printed as a charlist if it is printable, otherwise as list.