0

I have tried various ways to generate a list like:

 n = 3
 nodelist_master = Enum.into 1..n, []

But when I try and output them with IO.puts "List: #{nodelist_master}" or inspect I get

 ^A^B^C

I was expecting

 [1,2,3]
Edward Hasted
  • 3,201
  • 8
  • 30
  • 48
  • Can you post the `inspect` code that doesn't work? – Dogbert Apr 21 '18 at 10:33
  • My guess is he is tying`IO.puts nodelist_master` (which does give the output he reports) rather than simply `nodelist_master` which gives `[1,2,3]`. when you convert the list to string it gets interpreted as code-point command chars. – GavinBrelstaff Apr 21 '18 at 11:35
  • IO.inspect "List: #{nodelist_master}" which gives the same result as listed whereas IO.inspect nodelist_master works. Why should there be a difference? – Edward Hasted Apr 21 '18 at 11:37
  • @EdwardHasted https://stackoverflow.com/questions/30037914/elixir-lists-interpreted-as-char-lists Basically simple answer is that when return codes from Erlang are passed back they're charlists. Elixir usually wants to treat them as binaries--saves a lot of time when parsing error messages. Those who built Elixir originally often had the need to see the charlists as their corresponding binaries and they knew how to get the other form back if they needed it. – Onorio Catenacci Apr 23 '18 at 14:42
  • Does this answer your question? [Elixir lists interpreted as char lists](https://stackoverflow.com/questions/30037914/elixir-lists-interpreted-as-char-lists) – Adam Millerchip Mar 29 '21 at 06:22

1 Answers1

4

String interpolation you used ("#{list}") implicitly calls Kernel.to_string/1 on the argument.

iex|1 ▶ list = Enum.into 1..3, []
#⇒ [1, 2, 3]
iex|2 ▶ to_string(list)        
#⇒ <<1, 2, 3>>

Lists of integers are output as ASCII chars for values < 127:

iex|3 ▶ IO.puts to_string(list)
#⇒ ^A^B^C
:ok

The above are ASCII codes for 1, 2, and 3 respectively. For 65 (which is ASCII code for "A" char):

iex|3 ▶ IO.puts [65]
#⇒ A

IO.inspect implicitly calls Kernel.inspect/2 on the argument:

iex|4 ▶ inspect(list)
#⇒ "[1, 2, 3]"
iex|5 ▶ IO.inspect list, label: "List"
#⇒ List: [1, 2, 3]
[1, 2, 3]
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160