在Elixir中将整数列表打印为String

编程入门 行业动态 更新时间:2024-10-27 09:41:49
本文介绍了在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

本文发布于:2023-11-26 16:38:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634404.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   中将   列表   Elixir   String

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!