Elixir Tuples

From Elixir Wiki
Jump to navigation Jump to search

Elixir Tuples[edit]

Tuples in Elixir are ordered collections of values that can contain any type of data. Unlike lists, tuples are fixed in length and cannot be modified once created. In Elixir, tuples are defined using curly braces and comma-separated values. Here's an example of a tuple:

```elixir tuple = {:name, "John", :age, 30} ```

Tuples are commonly used in Elixir to represent structured data and can be accessed using pattern matching or by using the `elem/2` function. Let's explore these concepts further.

Pattern Matching[edit]

Pattern matching is a powerful feature in Elixir that allows us to decompose data structures and bind their values to variables. We can match specific elements of a tuple using pattern matching. Here's an example:

```elixir {:name, name, :age, age} = tuple ```

In this example, we're matching the tuple against a pattern that consists of four elements. The variables `name` and `age` will be bound to the corresponding values in the tuple.

Accessing Tuple Elements[edit]

To access specific elements of a tuple, we can use the `elem/2` function. The function takes a tuple and an index as arguments and returns the value at that index. Indices in Elixir are zero-based, meaning the first element is at index 0. Here's an example:

```elixir name = elem(tuple, 1) age = elem(tuple, 3) ```

In this example, `name` will be assigned the value "John" and `age` will be assigned the value 30.

Tuple Functions[edit]

Elixir provides several functions for working with tuples:

  • `tuple_size/1`: Returns the number of elements in a tuple.
  • `put_elem/3`: Returns a new tuple with a specific element replaced.
  • `tuple_concat/2`: Concatenates two tuples.
  • `tuple_to_list/1`: Converts a tuple to a list.
  • `list_to_tuple/1`: Converts a list to a tuple.

Use Cases[edit]

Tuples are commonly used in Elixir for various purposes, such as:

  • Representing key-value pairs.
  • Returning multiple values from a function.
  • Bundling related data together.
  • Parts of data structures like maps or structs.

In summary, tuples in Elixir are ordered collections of values with fixed length. They can be accessed using pattern matching or the `elem/2` function. Tuples are widely used in Elixir to represent structured data and have various applications in different contexts.

See Also[edit]