解构 Elixir 中的整数列表后出现意外的尾部值

发布于 2025-01-21 03:30:35 字数 365 浏览 1 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ぽ尐不点ル 2025-01-28 03:30:35

您的输出实际上是[7,8] ...它只是重新形成了。

这也许是长生不老药中最令人困惑的事情之一,但是有一个历史原因。请密切注意您在输出中看到的单引号:它们指示a charlist ,它是未编码的编码codepoints(是从Erlang没有对字符串的内置支持的时候。 CodePoints表示Unicode字符。 Elixir试图通过将其成员组成的整数在ASCII范围内的整数组成时,通过将列表格式化为可读的列表来提供一些向后兼容。您可以将此格式行为覆盖为io.inspect/2的选项:

iex> IO.inspect([7, 8], charlists: :as_lists)
[7, 8]  # <--- there is your list!
'\a\b'  # <--- here is the attempt at making it human-readable

iex> IO.inspect('cat', charlists: :as_lists)
[99, 97, 116]
'cat'

此行为仅在列表包含ASCII范围内的整数时才会启动。当成员不在ASCII范围内时,不需要特殊选项来自定义格式化,例如

iex> IO.inspect([1001, 1002, 1003])
[1001, 1002, 1003]
[1001, 1002, 1003]

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:

iex> IO.inspect([7, 8], charlists: :as_lists)
[7, 8]  # <--- there is your list!
'\a\b'  # <--- here is the attempt at making it human-readable

iex> IO.inspect('cat', charlists: :as_lists)
[99, 97, 116]
'cat'

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.

iex> IO.inspect([1001, 1002, 1003])
[1001, 1002, 1003]
[1001, 1002, 1003]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文