1

I am pretty new to Elixir so I am sure I am making a rookie mistake here somewhere but this behavior seems a bit odd to me.

This issue is best demonstrated with an example.

I have a nested list of the following form.

raw_list = [[123, "The Hobbit", 456, "JRR Tolkien"]]

When I perform the following map on this list

items = Enum.map(raw_list, fn [book_id, book_title, author_id, author_title] -> 
         %{
           book_id: book_id, 
           book_title: book_title, 
           author_id: author_id, 
           author_title: author_title
          } end)

items now equals the following (which is expected)

[
    %{
        author_id: 456,
        author_title: "JRR Tolkien",
        book_id: 123,
        book_title: "The Hobbit"
     }
]

The issue here is if I run the following map over that items list

Enum.map(items, fn item -> item.book_id end)

which returns

'{'

It seems like elixir thinks it should treat item.author_id as a string, so it gets the ASCII character for the value of 123 which is '{'

The weird part is that if I run

Enum.map(items, fn item -> item.author_id end)

elixir returns

[456]

Which is what I expect...

Any idea what's going on here?

Justin Wood
  • 9,941
  • 2
  • 33
  • 46
Kulix
  • 444
  • 3
  • 12
  • It is just a matter of representation. Try `IO.inspect([123], charlists: false)` to get the expected output. This answer may also interest you: https://stackoverflow.com/a/30039460/3044673 – bla Apr 16 '18 at 02:33
  • But what about `Enum.map(items, fn item -> item.author_id end)` returning [456]. Wouldn't we expect that to return a character representation instead of a list representation? – Kulix Apr 16 '18 at 02:38
  • 1
    I did not find any documentation to confirm, but I believe that printable values on the ASCII table are shown as characters by default. This other answer may shed a little more light into the issue: https://stackoverflow.com/questions/32804904/how-to-print-out-a-maps-array-values-in-elixir#32806531 – bla Apr 16 '18 at 02:55
  • Yeah, I think you are right! If you type `[123]` into an IEX session, it prints as `{`. Weird. I think this is purely representational though, since when you do operations on that data it is treated properly as a list with one integer item. – Kulix Apr 16 '18 at 02:55

0 Answers0