i wrote a simple program like this. I see strange behavior
listks = [8,9,10]
IO.inspect(listks, label: "My Label")
When i run the above program, the display output is ‘\b\t\n\v’
If i run the same program with listks as [1,2,3] the display output is correct.
This is expected behaviour and a known “gotcha” for new Elixir developers.
See Is there a way to inspect a list of integers without accidentally ending up with a charlist? for an explanation and solution.
IO.inspect is infering the list as chartists and printing as same. This is the default behaviour for
:charlists - when
:as_charlists all lists will be printed as charlists, non-printable elements will be escaped.When
:as_lists all lists will be printed as lists. When the default
:infer, the list will be printed as a charlist if it is printable, otherwise as list. See
List.ascii_printable?/1 to learn when a charlist is printable.
Inspect can be configured - Inspect.Opts — Elixir v1.13.2 . Multiple ways to achieve this:
- You can pass the additional options to
inspect at runtime when invoking
IO.inspect(listks, label: "My Label", charlists: :as_lists)
- You can add
IEx.configure(inspect: [charlists: :as_lists]) in
.iex.exs file - if you need this only for dev iex sessions.
- From elixir 1.13 onwards - default_inspect_fun/1 can be set.
You can read more from this blog -
For every project, I add the following configuration in
.iex.exs file. This helps for my iex sessions during development.
# .iex.exs file in root folder of project.
IEx.configure(inspect: [charlists: :as_lists])
You can learn about
.iex.exs file from docs - .iex.exs
When starting, IEx looks for a local
.iex.exs file (located in the current working directory), then a global one (located at
~/.iex.exs ) and loads the first one it finds (if any).