Elixir 列表被解释为字符列表 [英] Elixir lists interpreted as char lists

查看:20
本文介绍了Elixir 列表被解释为字符列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始使用 Elixir.我正在使用 ExUnit 为我自己实现的简单 Enumerable 函数编写一些测试,而不使用标准的 Enum 模块.

I'm just starting out with Elixir. I'm writing some tests using ExUnit for simple Enumerable functions that I am implementing myself, without using the standard Enum module.

在我的测试中,我发现每当我引用列表 [7, 8, 9] 时,一旦它在标准输出中打印,我就会看到字符列表 'a '.为什么会发生这种事情?

In my tests I'm finding that whenever I reference the list [7, 8, 9], once it is printed in in stdout I am seeing the char list 'a '. Why does this sort of thing happen?

推荐答案

Elixir 有两种字符串:二进制(双引号)和字符列表(单引号).后一种变体继承自 Erlang,内部表示为整数列表,映射到字符串的代码点.

Elixir has two kinds of strings: binaries (double quoted) and character lists (single quoted). The latter variant is inherited from Erlang and is internally represented as a list of integers, which map to the codepoints of the string.

当您使用 inspectIO.inspect 等函数时,Elixir 会尝试变得聪明并将整数列表格式化为字符串以便于阅读.但是,在某些情况下,您最终会得到一个无意义的字符串,因为列表中的所有整数都恰好是有效的代码点.例如,字符 A 到 Z 在 ASCII 中表示为整数 65 到 90.

When you use functions like inspect and IO.inspect, Elixir tries to be smart and format a list of integers as a string for easy readability. However, in some cases you end up with a nonsense string just because all of the integers in your list happen to be valid codepoints. For example, the characters A through Z are represented as the integers 65 through 90 in ASCII.

iex> IO.inspect [65, 66, 67]
'ABC'

如果你想打印一个原始列表,你可以使用 charlists: :as_lists 选项.要查看完整的选项列表,请打开 iex 并输入 h Inspect.Opts.

If you like to print a raw list, you can use the charlists: :as_lists option. For a full list of options fire up iex and type h Inspect.Opts.

iex> IO.inspect [65, 66, 67], charlists: :as_lists
[65, 66, 67]

使用 Elixir <1.4,可以使用char_lists: false.

With Elixir < 1.4, you can use char_lists: false.

顺便说一下,这并不是 Elixir 对您隐藏底层构建块的唯一情况,二进制文件(双引号字符串)和结构也会发生这种情况.

By the way, this is not the only case where Elixir hides the underlying building blocks from you, it also happens with binaries (double quoted strings) and structs.

更深层次的原因是 Elixir 和 Erlang 没有用户定义的类型,因此无法区分列表和单引号字符串,因为两者都只是列表.但是,这在其他情况下也可能是一种优势.例如,它允许我们在 Elixir 和 Erlang 中轻松序列化任何数据结构,因为它只能从语言附带的基本构建块构建.

The deeper reason for this is that Elixir and Erlang do not have user-defined types, so there's no way to distinguish between a list and a single quoted string, because both are just lists. However, this can also be a strength in other situations. For example, it allows us to trivially serialize any data structure in Elixir and Erlang, because it can only be built from the basic building blocks that come with the language.

这篇关于Elixir 列表被解释为字符列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆