On Elixir Pt. 5

Jan 4, 2025

We are continuing our journey with composite data types, and in this article, we briefly touch on the next composite data type: Tuples.

Tuples are defined using {} and can hold any type of value.

Go ahead and create a file named tuple.ex. Open this file in your favorite text editor and write the following code in it:

tuple1 = {3, "hi"}
tuple2 = {0, {1, false}, 2.0, "three"}

IO.inspect(tuple1)
IO.inspect(tuple2)

Let’s run this program, and then I’ll explain. Use the following command to run the program:

$ elixir tuple.ex 
{3, "hi"}
{0, {1, false}, 2.0, "three"}

Explanation

  • The first two lines define the tuples tuple1 and tuple2, each containing values of different types. Even further, tuple2 contains a tuple!
  • Finally, as we know, we cannot use the IO.puts function to print the composite data type values. Instead, we have used the same IO.inspect function to inspect and print the values of tuple1 and tuple2.

---

From a user’s (or developer’s) perspective, both lists and tuples store the same types of values (though not internally in the same way). However, if you want to save a small number of values, such as two, three, or five, use tuples. For all other scenarios, use lists.

Tags: elixir