Understanding strings and lists

Hello,

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.

1 Like

The classic erlang string is represented as a list of bytes. ‘r’ is in fact [114]. This is called a charlists in elixir. (https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#charlists)

So
'hello'
and
[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 [114] this can be displayed as r whereas 114 is just an integer which it will print as an integer.

4 Likes

FYI:

iex(1)> cl = 'abc'
'abc'
iex(2)> IO.inspect(cl,[charlists: :as_charlists])
'abc'
'abc'
iex(3)> IO.inspect(cl,[charlists: :as_list])
[97, 98, 99]
'abc'
iex(4)> IO.inspect([97,98,99])                              
'abc'
'abc'
iex(5)> IO.inspect([114])
'r'
'r'
iex(6)> IO.inspect([114],[charlists: :as_list])
[114]
'r'
iex(7)> IO.inspect('r',[charlists: :as_charlists])
'r'
'r'
iex(8)> IO.inspect('r',[charlists: :as_list])     
[114]
'r'
iex(9)> 

Inspect.Opts:

4 Likes