Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir: Printing list along with string

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 image 377
palerdot Avatar asked Aug 05 '17 15:08

palerdot


People also ask

How do you print something 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.

How do I add to my list in Elixir?

In Elixir and Erlang we use `list ++ [elem]` to append elements.

How do you get the first element of a list in Elixir?

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.

How do you find the length of a list in Elixir?

The length() function returns the length of the list that is passed as a parameter.


2 Answers

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]
like image 153
Aleksei Matiushkin Avatar answered Oct 04 '22 00:10

Aleksei Matiushkin


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]
like image 32
Andy Gaskell Avatar answered Oct 04 '22 01:10

Andy Gaskell