4

I'm running the code below that adds the numbers in the list by 10. However, I am getting a list of chars.

result = Enum.map([1, 2, 3], fn x -> x + 10 end)

Result \w\f\r

If I change from + to * the code works fine. result = Enum.map([1, 2, 3], fn x -> x + 10 end) which returns [10, 20, 30] as expected.

However, the moment I change from 10 to 32, I also encounter a similar error which returns ' @'

Any idea what this means and how to fix it? Thanks

Ming
  • 332
  • 4
  • 17

2 Answers2

2

In Elixir, a char list (a value between two single quotes 'like this') is just a list of numbers. So, when you have a list of numbers where all of them can be written as characters (within ASCII range), iex will print them as such for you.

iex(1)> 'hello'
'hello'
iex(2)> [104, 101, 108, 108, 111]
'hello'

You still have a list of numbers, and you can still do other operations on it as if it were a list of numbers, such as

iex(3)> [104, 101, 108, 108, 111] == 'hello'
true
iex(4)> Enum.map 'hello', fn x -> x * 10 end
[1040, 1010, 1080, 1080, 1110]

If, within iex, you want to see the numeric values of your list, you can append a non-viewable character to your list, such as 0, which will force iex to display the numeric list instead of the char list.

iex(5)> [104, 101, 108, 108, 111] ++ [0]
[104, 101, 108, 108, 111, 0]

You can read more about char lists here

Justin Wood
  • 9,941
  • 2
  • 33
  • 46
  • 1
    thanks. I ended up using `IO.inspect([11, 12, 13], char_lists: false)` which was from a duplicate question. However, it does not seem to work for this. Any ideas? `IO.inspect(for n <- 1..10, multiple_of_3?.(n), do: n * n, char_lists: false)` returns `'\t$Q'` – Ming Nov 20 '16 at 09:43
0

In Elixir, a char list is a list containing code points, which can also be represented as a single-quoted string.

If your function returns a list of numbers, where those numbers are code points from within the ASCII table, IEx will represent them as a single-quoted string.

iex(5)> [11,12,13] '\v\f\r'

If at least one of them isn't an ASCII code point, they'll be represented as a list of numbers:

iex(22)> [11,12,127] [11, 12, 127]

It's an oddity of how Elixir (or elrang, I suppose) handles character lists and strings.

Veen
  • 33
  • 3
  • It's not really an "oddity" of how Elixir handles character lists. Error messages from Erlang are usually returned as character lists so it's quite handy to have the actual text displayed as opposed to codepoints. – Onorio Catenacci Nov 17 '16 at 17:41
  • True. I didn't mean oddity in a negative way. I meant at "a feature of Erlang that's different to how things are done in other languages". – Veen Nov 17 '16 at 18:30