list - 在 Elixir 的一行中列出不同类型的列表
问题描述
如何在 Elixir 的一行上打印一个列表。谢谢 :)
a = ["Hey", 100, 452, :true, "People"]
defmodule ListPrint do
def print([]) do
end
def print([head | tail]) do
IO.puts(head)
print(tail)
end
end
ListPrint.print(a)
#⇒ Hey
# 100
# 452
# :true
# People
我需要:
#⇒ Hey 100 452 :true People
解决方案
直接的解决方案是使用Enum.join/2
:
["Hey", 100, 452, :true, "People"]
|> Enum.join(" ")
|> IO.puts()
#⇒ Hey 100 452 true People
如果您想使用递归并一一打印元素,您可以使用IO.write/2
代替IO.puts/2
:
defmodule ListPrint do
def print([]), do: IO.puts("")
def print([head | tail]) do
IO.write(head)
IO.write(" ")
print(tail)
end
end
ListPrint.print(["Hey", 100, 452, :true, "People"])
#⇒ Hey 100 452 true People
旁注:两者都IO.puts/2
隐IO.write/2
式调用Kernel.to_string/1
(反过来调用String.Chars
参数上的协议实现)导致打印的原子没有前导冒号。甚至您的代码也会打印true
,而不是:true
. 为了保存结肠,应该改用IO.inspect/3
它,这是杂食性的。
IO.inspect(["Hey", 100, 452, :ok, "People"])
#⇒ ["Hey", 100, 452, :ok, "People"]
推荐阅读
- python - Python - 及时迭代并查看 DataFrame 是否包含特定日期
- docker - docker HTTP 客户端容器如何在启动时发送 HTTP 请求
- css - 在 MacOS 上强制滚动条可见性不适用于所有页面
- excel - 如何从范围内的唯一值创建图表
- extjs - 商店更新后 ExtJS 网格选择不刷新
- java - Java中如何以数组的形式访问和使用自定义类?
- google-cloud-platform - 有没有办法检查云运行服务上的 process.env 变量?
- powershell - 更改测试文件中的字母
- data-structures - 堆栈和算术评估
- pervasive - PERVASIVE - SQL Double - 日期请求