I would like to print a list along with a string identifier like
list = [1, 2, 3]
IO.puts "list is ", list
This does not work. I have tried few variations like
# this prints only the list, not any strings
IO.inspect list
# using puts which also does not work
IO.puts "list is #{list}"
In javascript, I could simply do console.log("list is ", list)
. I'm confused how I could achieve the same in elixir.
Like any other programming language, printing is an easy task in Elixir. With Elixir, you have to use the IO module, which is an Elixir device that handles inputs and outputs. With the IO. puts function, you can print to the console.
In Elixir and Erlang we use `list ++ [elem]` to append elements.
The head is the first element of a list and the tail is the remainder of a list. They can be retrieved with the functions hd and tl. Let us assign a list to a variable and retrieve its head and tail.
The length() function returns the length of the list that is passed as a parameter.
Starting with Elixir 1.4, IO.inspect/2
accepts label
option among others:
IO.inspect list, label: "The list is"
#⇒ The list is: [1, 2, 3]
Maybe there's a better way (I'm new to Elixir too) but this worked for me:
IO.puts(["list is ", Enum.join(list, " ")])
list is 1 2 3
Interpolation works too:
IO.puts("list is #{Enum.join(list, " ")}")
Edit: inspect seems to better than Enum.join for this use case:
IO.puts("list is #{inspect(list)}")
list is [1, 2, 3]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With