首页 > 解决方案 > 在 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

标签: listelixir

解决方案


直接的解决方案是使用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/2IO.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"]

推荐阅读