Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a Elixir tuple into a bitstring?

I am new to Elixir and have I am trying to print something to STDOUT using IO.puts. IO.puts requires chardata. I looked at the Elixir docs and didn't see a way to convert tuples to bitstrings. I know there has to be a way to do this but I haven't found any BIF that do this.

So I want to convert this: {"foo", "bar", "baz"} to this: "foobarbaz".

I am in the process of learning Elixir and Erlang so this is all pretty new to me.

Thanks in advance!

like image 893
Stratus3D Avatar asked Oct 24 '13 17:10

Stratus3D


2 Answers

Usually we use tuples to hold a fixed amount of data, known up-front. So if you want to print the contents of a tuple, I would recommend doing:

def print_tuple({ foo, bar, baz }) do
  IO.puts foo <> bar <> baz
end

If the tuple you want to print has a dynamic size, it is very likely you want to use a list instead. You can convert the elements of a list to a binary using many functions, for example, Enum.join/2:

IO.puts Enum.join(list)

If you are absolutely sure you want to print the tuple contents, you can do:

IO.puts Enum.join(Tuple.to_list(tuple))

Keep in mind you can print any Elixir data structure by using IO.inspect/1.

like image 58
José Valim Avatar answered Sep 30 '22 15:09

José Valim


Enum.join creates a bitstring composed of the consecutive elements of a list. Convert the tuple to a list first. Using the |> (pipe) operator may improve readability:

{"foo", "bar", "baz"} |> Tuple.to_list |> Enum.join  # "foobarbaz"

You can also specify a delimiter:

{"foo", "bar", "baz"} |> Tuple.to_list |> Enum.join(", ")  # "foo, bar, baz"
like image 43
falood Avatar answered Sep 30 '22 13:09

falood