为什么对x<-3..4执行以下操作:x * 3 return&#39; \ t \ f&#39;在长生不老药? [英] Why does for x &lt;- 3..4, do: x * 3 return &#39;\t\f&#39; in Elixir?
问题描述
在Elixir中,为什么对x<-3..4的理解会执行:x * 2
会导致 [6,8]
但会导致对于x<-3..4,请执行:x * 3
导致'\ t \ f'
吗?
In Elixir, why does the comprehension for x <- 3..4, do: x * 2
result in [6, 8]
but for x <- 3..4, do: x * 3
results in '\t\f'
?
我正在 iex
副本中执行此操作.
I'm executing this in the iex
repl.
推荐答案
这是Elixir中最令人困惑的陷阱之一:字符列表.请参阅这篇文章针对围绕同一问题的问题.
This is one of the most confusing gotchas in Elixir: the "humanizing" of charlists. See this post for a question revolving around this same issue.
字符列表是整数代码点的列表,用于表示未编码的字符串(从烘焙编码的日子开始,在较旧的Erlang库中更常见).因此,如果您有一个整数列表,Elixir(出于历史原因)必须猜测您是否要表示一个字符串"-因此,如果该列表中的所有整数都小于127,Elixir认为这必须是一个表示字符串"数据的字符列表,并打印出相应的ASCII字符以使字符串可读.
Charlists are lists of integer codepoints, used to represent un-encoded strings (more common in older Erlang libraries from the days before encodings were baked in). So if you have a list of integers, Elixir (for historical reasons), has to guess whether or not you meant to represent a 'string' -- so if all the integers in that list are below 127, Elixir assumes that this must be a charlist that represents 'string' data and it prints out the corresponding ASCII characters to make a readable string.
您可以通过在对 IO.inspect/2
:
iex(1)> result = for x <- 3..4, do: x * 3
'\t\f'
iex(2)> IO.inspect(result, charlists: :as_lists)
[9, 12]
'\t\f'
或更简单地说:
iex> IO.inspect([9, 12], charlists: :as_lists)
[9, 12]
'\t\f'
这向我们显示了预期的整数(9、12),如果我们不愿意在Unicode或ASCII码图表中查找它们,我们会看到 \ t
和 \f
个字符分别由代码点9和12表示.
This shows us the expected integers (9, 12), and if we bother to look these up in a Unicode or ASCII code chart, we would see that the \t
and \f
characters are represented by codepoints 9 and 12 respectively.
请记住,这些数据表示形式只是视觉上的-基础数据是100%相同的:
Keep in mind that these representations of the data are just visual -- the underlying data is 100% the same:
iex> [9, 12] === '\t\f'
true
这篇关于为什么对x<-3..4执行以下操作:x * 3 return&#39; \ t \ f&#39;在长生不老药?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!