How to read tuples in Elixir
What is a tuple?
tuples hold numerous elements in a fixed-size container.
tuples are not supported by enum functions.
What is tuple used for?
-
tuplesare used when a function has numerous return values. -
They are also used to handle errors.
Syntax
tuple1 = {}
Functions for manipulating tuples
elem/2: This is an index-based access to a tuple.
put elem/3: This adds a value by index into a tuple.
tuple size/1: This is a function that returns the number of elements in a tuple.
An example of how to read a tuple
data_tuple = {"Dib", "Zim", 10, 3.14}tuple = elem(data_tuple, 0)IO.inspect tupletuple = elem(data_tuple, 2)IO.inspect tuple
Explanation
From the above example:
-
Line 1: We create a variable and store data inside the
tuple. -
Line 2: We use the
elem/2method (which we explain in the function heading above) to read thedata_tuplevariable. We also pass an index of the element we want to read. Then, we save it in thetuplevariable. -
Line 3: We use
IO.inspectto output our result.