Printing lists in elixir

0

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.

Guide me

Sincerley, Arvind

Hi,

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.

5 Likes

IO.inspect is infering the list as chartists and printing as same. This is the default behaviour for inspect.

: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:

  1. You can pass the additional options to inspect at runtime when invoking
IO.inspect(listks, label: "My Label", charlists: :as_lists)
  1. You can add IEx.configure(inspect: [charlists: :as_lists]) in .iex.exs file - if you need this only for dev iex sessions.
  2. 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).

4 Likes