11

I was trying my hand on Enum.map. I found this weird output, when I added 100 to all the elements of the list.

Terminal Screenshot

Why such an output? It turns out that I am getting a string when I add 100 but works just fine when I do other operation. I fiddled some more, I still got unexpected results like this.

Terminal Screenshot 2

Sheharyar
  • 73,588
  • 21
  • 168
  • 215
srajappa
  • 484
  • 8
  • 19
  • 3
    Possible duplicate of [Elixir lists interpreted as char lists](http://stackoverflow.com/questions/30037914/elixir-lists-interpreted-as-char-lists) – Dogbert Oct 30 '16 at 04:27

1 Answers1

23

The value you see 'efgh' is not a String but a Charlist.

The result of your statement should be [101, 102, 103, 104] (and it actually is), but it doesn't output it that way. The four values in your list map to e, f, g and h in ASCII, so iex just prints their codepoints instead of the list. If the list contains invalid characters (such as 0, or 433 like in your case), it leaves it as a simple list.

From Elixir's Getting Started guide:

A char list contains the code points of the characters between single-quotes (note that by default IEx will only output code points if any of the chars is outside the ASCII range).


Both 'efgh' and [101, 102, 103, 104] are equal in Elixir, and to prove that you can force inspect to print them as a List instead:

[101, 102, 103, 104] == 'efgh'
#=> true

[101, 102, 103, 104] |> inspect(charlists: :as_lists)
#=> [101, 102, 103, 104]

You can also configure IEx to always print charlists as lists:

IEx.configure(inspect: [charlists: :as_lists])

You can either call the above manually in a running IEx session or add it to an .iex.exs file to ensure it is always applied in one of the following ways:

  • Current Project: Add it to a file called .iex.exs in the same directory as your mix.exs file
  • All Projects: Add to an .iex.exs file in your home folder (i.e located at ~/.iex.exs.)
Sheharyar
  • 73,588
  • 21
  • 168
  • 215
  • 1
    Wow! Thanks for this smooth answer. I had ignored this part while posting this question. Thanks again! – srajappa Oct 30 '16 at 00:42
  • 5
    You can also configure IEx (through the `~/.iex.exs`) to *always* inspect the charlists as lists of integers, with `IEx.configure inspect: [charlists: :as_lists]` – Hécate Oct 30 '16 at 11:58
  • how do you configure the global charlist in testing? – krivar Jan 23 '20 at 11:37