在 Elixir 的一行中列出不同类型

List with different type on one line in 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/2IO.write/2 都隐式调用 Kernel.to_string/1 (which in turn calls the implementation of String.Chars protocol on the argument,) resulting in atoms printed without leading colon. Even your code would print true, not :true. To preserve colon, one should use IO.inspect/3,这是杂食性的。

IO.inspect(["Hey", 100, 452, :ok, "People"])  
#⇒ ["Hey", 100, 452, :ok, "People"]

IO.puts/2 向传递的任何字符串添加换行符。
如果您不想要换行符,请使用 IO.write/2
如:

a = ["Hey", 100, 452, :true, "People"]
defmodule ListPrint do
   def print([]) do
   end
   def print([head | tail]) do 
      IO.write(to_string(head) <> " ")
      print(tail)
   end
end
ListPrint.print(a)