0

I try to convert a list of strings into a list of integers. Here's the code:

list = ["114"]
list |> Enum.map(&String.to_integer(&1))

But the last line returns 'r'. While String.to_integer("114") returns 114 I tried Integer.parse/1, but it also gave me 'r' (which its character code is 114):

list
|> Enum.map(&Integer.parse(&1))
|> Enum.map(fn {num, _} -> num end)

Why?

  • That's as expected. As noted by the single quotes, that's a charlist, which is equal to the list of integers you expect. You can perform operations on it however you need, it will just be displayed as a charlist, but it's just `[114]` – sbacarob Jan 19 '21 at 15:51
  • 1
    Check out this question and the answer as well as links in the answer https://stackoverflow.com/questions/63473722/elixir-comprehension-returning-a-star-character/63476012#63476012 – sbacarob Jan 19 '21 at 15:51
  • 2
    If you want to see the numbers in IEx instead of charlists you can configure how they're inspected: `IEx.configure(inspect: [charlists: :as_lists])` – Brett Beatty Jan 19 '21 at 15:59
  • Just adding this guide as a reference, I think it explains it quite well: https://elixir-lang.org/getting-started/binaries-strings-and-char-lists.html#charlists – sabiwara Jan 20 '21 at 00:58

1 Answers1

1

As the other comments have pointed out, this confusing behavior is the result of Elixir "humanizing" charlists. In a nutshell, Elixir (for historical reasons) can store un-encoded strings as lists of integers (called "charlists"). The take-away is that when all the members of a list are integers in the ASCII range (i.e. 0-127), then Elixir formats the display using the corresponding codepoints for each integer (114 corresponds to r, for example).

See this answer for similar explanation: Why does for x <- 3..4, do: x * 3 return '\t\f' in Elixir?

Everett
  • 8,746
  • 5
  • 35
  • 49