在Elixir中将整数列表打印为String [英] Integer List printed as String in Elixir

查看:100
本文介绍了在Elixir中将整数列表打印为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试操作 Enum.map 。当我将100添加到列表的所有元素时,我发现了这个奇怪的输出。

I was trying my hand on Enum.map. I found this weird output, when I added 100 to all the elements of the list.

为什么这样的输出?事实证明,当我加100时我得到一个字符串,但是当我执行其他操作时效果很好。我摆弄了一些东西,仍然得到了这样的意外结果。

Why such an output? It turns out that I am getting a string when I add 100 but works just fine when I do other operation. I fiddled some more, I still got unexpected results like this.

推荐答案

您看到的'efgh'的值不是字符串,而是 Charlist

The value you see 'efgh' is not a String but a Charlist.

语句的结果应为 [101、102、103、104] (实际上是),但不是这样输出。列表中的四个值映射为 e f g h 的ASCII码,因此 iex 只打印其 codepoints 而不是列表。如果列表包含无效字符(例如0或433,例如您的情况),则将其保留为简单列表。

The result of your statement should be [101, 102, 103, 104] (and it actually is), but it doesn't output it that way. The four values in your list map to e, f, g and h in ASCII, so iex just prints their codepoints instead of the list. If the list contains invalid characters (such as 0, or 433 like in your case), it leaves it as a simple list.

从Elixir的入门指南


一个字符列表包含单引号之间字符的代码点(请注意,默认情况下,如果任何一个字符在ASCII之外,则IEx仅输出代码点范围)。

A char list contains the code points of the characters between single-quotes (note that by default IEx will only output code points if any of the chars is outside the ASCII range).






都是'efgh' [101、102、103、104] 在Elixir中相等,并证明可以强制检查将其打印为列表:


Both 'efgh' and [101, 102, 103, 104] are equal in Elixir, and to prove that you can force inspect to print them as a List instead:

[101, 102, 103, 104] == 'efgh'
#=> true

[101, 102, 103, 104] |> inspect(charlists: :as_lists)
#=> [101, 102, 103, 104]






您还可以将IEx配置为始终将字符列表打印为列表:

IEx.configure(inspect: [charlists: :as_lists])

这篇关于在Elixir中将整数列表打印为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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