Enum.filter BUG?!

I run these lines under iex:

iex(62)> Enum.filter([1, 1000], fn(x) -> rem(x, 2) == 0 end)
[1000] #ok
iex(63)> Enum.filter([1, 75], fn(x) -> rem(x, 2) == 0 end)  
[] #ok
iex(65)> Enum.filter([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)
[2] #ok
iex(66)> Enum.filter([1, 75], fn(x) -> rem(x, 2) == 0 end)  
[] #ok
iex(67)> Enum.filter([1, 1000], fn(x) -> rem(x, 2) == 0 end)
[1000] #ok
iex(68)> Enum.filter([1, 50], fn(x) -> rem(x, 2) == 0 end)  
'2' # what ?!
iex(69)> Enum.filter([1, 100], fn(x) -> rem(x, 2) == 0 end)
'd' # what ?!
iex(70)> Enum.filter([1, 80], fn(x) -> rem(x, 2) == 0 end) 
'P' what ?!

What’s up this 50, 60,70 … 100 and so on ? :slight_smile:

50 ASCII for 2
it thinks it’s a charlist
‘2’ == [50]

2 Likes

This is a common issue explained best by https://github.com/elixir-lang/elixir/wiki/FAQ#4-why-is-my-list-of-integers-printed-as-a-string

Why is my list of integers printed as a string?

For example:

iex(1)> [27, 35, 51]
'\e#3'

Pretty-printing of lists is done by using Erlang’s native function. It is designed to print lists as strings when all elements of the list are valid ASCII codes.

You can avoid this by appending 0 to your list, or by disabling char list printing:

iex(2)> [27, 35, 51] ++ [0]
[27, 35, 51, 0]
iex(3)> inspect [27, 35, 51], char_lists: :as_lists
"[27,35,51]"

Also see this post to the Elixir-Lang mailing list for a bit more on the reasoning behind this design choice: https://groups.google.com/d/msg/elixir-lang-talk/0xxH9HxdQnU/LHgK8elhEQAJ

There’s also the i/1 helper in iex, that may give you some additional information about any value.

4 Likes

This a little bit annoying if you don’t set IEx.configure inspect: [char_lists: false] Thanks for solution :smile:

1 Like