List with different type on one line in Elixir

How to print a list on one line in Elixir. Thank you :)

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

I need:

#⇒ Hey 100 452 :true People

Upvotes: 0

Views: 281

Answers (2)

Mark McElroy
Mark McElroy

Reputation: 373

IO.puts/2 adds a newline to any string passed.
If you do not want the newline, use IO.write/2
such as:

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)

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

The straightforward solution would be to use Enum.join/2:

["Hey", 100, 452, :true, "People"]
|> Enum.join(" ")
|> IO.puts()
#⇒ Hey 100 452 true People

If you want to use recursion and print elements one by one, you might use IO.write/2 instead of 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

Sidenote: both IO.puts/2 and IO.write/2 implicitly call 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 instead, which is omnivorous.

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

Upvotes: 1

Related Questions