Tuple

From Elixir Wiki
Jump to navigation Jump to search

Tuple[edit]

A tuple is an ordered collection of elements that can be of different data types in the Elixir programming language. Tuples are immutable, meaning that once defined, their elements cannot be modified or removed. They provide a convenient way to store and manipulate related data.

Syntax[edit]

Tuples are defined using curly brackets ({}) and comma-separated values. The following is an example of a tuple:

``` {1, "Hello", :world} ```

Elements within a tuple can be accessed using the dot notation along with the index position. The index position starts from 0 for the first element. For example:

``` tuple = {1, "Hello", :world} IO.puts(tuple.1) # Output: 1 IO.puts(tuple.2) # Output: "Hello" IO.puts(tuple.3) # Output: :world ```

Tuple Operations[edit]

Tuples support various operations in Elixir. Some of the commonly used operations include:

Size[edit]

The `Tuple.size/1` function returns the number of elements in a tuple. For example:

``` tuple = {1, "Hello", :world} IO.puts(Tuple.size(tuple)) # Output: 3 ```

Concatenation[edit]

Tuples can be concatenated using the `++/2` operator. The resulting tuple contains all the elements of both tuples. For example:

``` tuple1 = {1, 2} tuple2 = {3, 4} concatenated = tuple1 ++ tuple2 IO.inspect(concatenated) # Output: {1, 2, 3, 4} ```

Element Replacement[edit]

Although tuples are immutable, an element at a specific index can be replaced by creating a new tuple with desired changes. For example:

``` tuple = {1, 2, 3} replaced = put_elem(tuple, 1, "Hello") IO.inspect(replaced) # Output: {"Hello", 2, 3} ```

Use Cases[edit]

Tuples are commonly used in Elixir for various purposes, including:

  • Returning multiple values from a function.
  • Representing coordinates or points in a 2D or 3D space.
  • Storing related configuration options.
  • Grouping related data together.

Using tuples can provide a cleaner and more expressive codebase in certain scenarios.

Summary[edit]

Tuples in Elixir are immutable, ordered collections that allow storing different data types. They can be accessed using index notation and support operations like size calculation, concatenation, and element replacement. Tuples have several use cases, making them a valuable data structure in Elixir programming.

See Also[edit]

  • List - An ordered collection of elements that can be dynamically modified.
  • Map - A key-value store for efficient data lookup and modification.
  • Keyword - An associative list with named keys for easy data retrieval.
  • Struct - A data structure for defining custom types with named fields.