Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

Integer List printed as String in Elixir

I was trying my hand on Enum.map. I found this weird output, when I added 100 to all the elements of the list.

Terminal Screenshot

Why such an output? It turns out that I am getting a string when I add 100 but works just fine when I do other operation. I fiddled some more, I still got unexpected results like this.

Terminal Screenshot 2

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The value you see 'efgh' is not a String but a Charlist.

The result of your statement should be [101, 102, 103, 104] (and it actually is), but it doesn't output it that way. The four values in your list map to e, f, g and h in ASCII, so iex just prints their codepoints instead of the list. If the list contains invalid characters (such as 0, or 433 like in your case), it leaves it as a simple list.

From Elixir's Getting Started guide:

A char list contains the code points of the characters between single-quotes (note that by default IEx will only output code points if any of the chars is outside the ASCII range).


Both 'efgh' and [101, 102, 103, 104] are equal in Elixir, and to prove that you can force inspect to print them as a List instead:

[101, 102, 103, 104] == 'efgh'
#=> true

[101, 102, 103, 104] |> inspect(charlists: :as_lists)
#=> [101, 102, 103, 104]

You can also configure IEx to always print charlists as lists:

IEx.configure(inspect: [charlists: :as_lists])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...