我正在尝试操作 Enum.map 。当我将100添加到列表的所有元素时,我发现了这个奇怪的输出。
I was trying my hand on Enum.map. I found this weird output, when I added 100 to all the elements of the list.
为什么这样的输出?事实证明,当我加100时我得到一个字符串,但是当我执行其他操作时效果很好。我摆弄了一些东西,仍然得到了这样的意外结果。
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.
推荐答案
您看到的'efgh'的值不是字符串,而是 Charlist 。
The value you see 'efgh' is not a String but a Charlist.
语句的结果应为 [101、102、103、104] (实际上是),但不是这样输出。列表中的四个值映射为 e , f , g 和 h 的ASCII码,因此 iex 只打印其 codepoints 而不是列表。如果列表包含无效字符(例如0或433,例如您的情况),则将其保留为简单列表。
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.
从Elixir的入门指南:
一个字符列表包含单引号之间字符的代码点(请注意,默认情况下,如果任何一个字符在ASCII之外,则IEx仅输出代码点范围)。
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).
都是'efgh'和 [101、102、103、104] 在Elixir中相等,并证明可以强制检查将其打印为列表:
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]
您还可以将IEx配置为始终将字符列表打印为列表:
IEx.configure(inspect: [charlists: :as_lists])更多推荐
在Elixir中将整数列表打印为String
发布评论