Elixir: Strange behaviour of Enum.chunk

Created on 26 Jan 2017  路  4Comments  路  Source: elixir-lang/elixir

I'm running Elixir 1.4.0 and Erlang 19.2 on 10.12.2 macOS Sierra

Example:

iex(27)> Enum.chunk([1, 2, 3, 4, 5, 6], 2)
[[1, 2], [3, 4], [5, 6]]
iex(29)> Enum.chunk([1, 2, 3, 4, 5, 6, 711, 811], 2)
[[1, 2], [3, 4], [5, 6], [711, 811]]
iex(28)> Enum.chunk([1, 2, 3, 4, 5, 6, 7, 8], 2)
[[1, 2], [3, 4], [5, 6], '\a\b']

Expected output:

[[1, 2], [3, 4], [5, 6], [7,8]]

Could also be an Erlang issue since :lists.reverse/1 is used in the implementation and:

:lists.reverse([1, 2])
[2, 1]

while

:lists.reverse([8, 9])
'\t\b'

Edit: :lists.reverse/1 seems very straight forward

Most helpful comment

One correction on how to disable such printing: IEx.configure(inspect: [charlists: :as_lists]) should be used instead of :shell.strings/1 function.

All 4 comments

It's not an issue with Enum.chunk/2. Try typing out the resulting list as a literal in iex and you'll see the same result. This is due to how Erlang represents strings (as lists of integers) and therefore how it's displayed in the shell. Basically, your list still contains the same numbers, but because they can be representative of a character, your shell will assume that's what you meant. If you want to disable this, look into the :shell.strings/1 function.

I would also advise to try out the i/1 IEx helper on any term. In this particular case, it explains what @skovsgaard said.

iex> i(:lists.reverse([8, 9]))
Term
  '\t\b'
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, 8]
Reference modules
  List
Implemented protocols
  IEx.Info, Collectable, Enumerable, Inspect, List.Chars, String.Chars

One correction on how to disable such printing: IEx.configure(inspect: [charlists: :as_lists]) should be used instead of :shell.strings/1 function.

You're right. I was thinking in Erlang.

Was this page helpful?
0 / 5 - 0 ratings