解构 Elixir 中的整数列表后出现意外的尾部值
iex(1)> [foo|bar] = [2,3,4,5,6,7]
[2, 3, 4, 5, 6, 7]
iex(2)> foo
2
iex(3)> bar
[3, 4, 5, 6, 7]
iex(4)> [foo|bar] = [6,7,8]
[6, 7, 8]
iex(5)> foo
6
iex(6)> bar
'\a\b'
我本来希望bar
最终将为[7,8]
,但是它具有值'\ a \ b'
。
我是长生不老药的新手,正在寻找解释为什么这是。 我正在运行Elixir 1.13.3
。
iex(1)> [foo|bar] = [2,3,4,5,6,7]
[2, 3, 4, 5, 6, 7]
iex(2)> foo
2
iex(3)> bar
[3, 4, 5, 6, 7]
iex(4)> [foo|bar] = [6,7,8]
[6, 7, 8]
iex(5)> foo
6
iex(6)> bar
'\a\b'
I would have expected bar
to be [7,8]
in the end, however it has the value '\a\b'
.
I'm new to Elixir and looking for an explanation why this is.
I'm running Elixir 1.13.3
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的输出实际上是
[7,8]
...它只是重新形成了。这也许是长生不老药中最令人困惑的事情之一,但是有一个历史原因。请密切注意您在输出中看到的单引号:它们指示a charlist ,它是未编码的编码codepoints(是从Erlang没有对字符串的内置支持的时候。 CodePoints表示Unicode字符。 Elixir试图通过将其成员组成的整数在ASCII范围内的整数组成时,通过将列表格式化为可读的列表来提供一些向后兼容。您可以将此格式行为覆盖为
io.inspect/2
的选项:此行为仅在列表包含ASCII范围内的整数时才会启动。当成员不在ASCII范围内时,不需要特殊选项来自定义格式化,例如
Your output actually IS
[7, 8]
... it's just been re-formatted.This is perhaps one of the most confusing things in Elixir, but there is a historical reason for it. Pay close attention to the single quotes you see in the output: they indicate a charlist which is a list of unencoded codepoints (which are sort of old-Erlang versions of strings from a time when Erlang did not have built-in support for strings). Codepoints represent Unicode characters. Elixir is trying to offer some backwards compatibility with Erlang charlists by formatting lists as human-readable when its members consist of integers in the ASCII range. You can override this formatting behavior as an option for
IO.inspect/2
:This behavior only kicks in when the list contains integers in the ASCII range. No special options are necessary to customize the formatting when the members aren't in the ASCII range, e.g.