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

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

问题描述

我只是从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]时,将其打印在stdout中后,我都会看到字符列表'\a\b\t'.为什么会发生这种事情?

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\b\t'. 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]

有长生不老药< 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列表被解释为char列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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