Enum.chunk/4 question


Can anybody please explain me the next behaviour? Why with the integers list instead of 7 I am getting ‘\a’? Btw if I’ll add 8, 9, 10 etc it will be chars as well…

iex(88)> strings_list = ["a", "b", "c", "d", "e", "f", "g"]
["a", "b", "c", "d", "e", "f", "g"]
iex(89)>  Enum.chunk(strings_list,2,2,[])
[["a", "b"], ["c", "d"], ["e", "f"], ["g"]]
iex(90)> integers_list = [1,2,3,4,5,6,7]
[1, 2, 3, 4, 5, 6, 7]
iex(91)>  Enum.chunk(integers_list,2,2,[])
[[1, 2], [3, 4], [5, 6], '\a']

Elixir displays a list of integers that can be displayed as characters as a char list (see: http://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#char-lists)

Inspect’s default behaviour (that’s what iex uses to display the output) is to infer whether to print a char list or a list of integers, this can be managed.

iex> IO.inspect([7], charlists: :as_charlists)
iex> IO.inspect([7], charlists: :as_lists)
iex> IO.inspect([7], charlists: :infer)

You can also change the default IEx behaviour

iex> IEx.configure(inspect: [charlists: :as_lists])
iex> [7]

This can be placed in ~/.iex.exs to change the setting globally. (See http://elixir-lang.org/docs/stable/iex/IEx.html#module-configuring-the-shell)


To add to the excellent explanation above, try running IO.inspect([97,98,99])

ah, ok thanks! still could be confusing though, at least not a language bug! :slight_smile:

Think of it like in C or C++, you have an array of integers, you could display it as an array of integers or as a string (since a character in a string is just an integer). Same thing in Elixir, but by default it tries to display it as a string if the characters all fall within the visual character bounds, else it falls back to displaying it as an integer.

I also recommend to use i/1 IEx helper function if in doubt:

iex(1)> i('\a')
Data type
  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
Reference modules