Elm - Tuples

At times, there might be a need to store a collection of values of varied types. Elm gives us a data structure called tuple that serves this purpose.

A tuple represents a heterogeneous collection of values. In other words, tuples enable storing multiple fields of different types. A tuple stores fixed number of values. Tuples are useful when you want to return multiple values of different types from a function. These data structures are immutable like other types in elm.



A simple example is shown below −

> ("TuotrialsPoint",5,True,"Hyderabad")
("TuotrialsPoint",5,True,"Hyderabad") : ( String, number, Bool, String )

In our subsequent sections, we will learn about the different tuple operations.


This operation extracts the first value from a tuple.


Tuple.first tuple_name
> Tuple.first
<function> : ( a1, a2 ) -> a1


> Tuple.first (10,"hello")
10 : number


The second tuple operation extracts the second value from a tuple.


Tuple.second tuple_name
> Tuple.second
<function> : ( a1, a2 ) -> a2


> Tuple.second (10,"hello")
"hello" : String

List of tuples

A List can store Tuples. If tuples are used inside a list, make sure they all are of the same data type and have the same number of parameters.


> [("hello",20),("world",30)]
[("hello",20),("world",30)] : List ( String, number )

Tuple with function

A function can return tuples. In addition, tuples can be passed as parameters to functions.

Illustration 1

The following example defines a function fn_checkEven. This function accepts an integer value as parameter and returns a tuple.

> fn_checkEven no = \
   if no%2 == 0 then \
      (True,"The no is Even")\
   else \
      (False,"No is not even")
<function> : Int -> ( Bool, String )
> fn_checkEven 10
(True,"The no is Even") : ( Bool, String )
> fn_checkEven 11
(False,"No is not even") : ( Bool, String )

Illustration 2

The following passes a tuple as a parameter to a function.

> fn_add (a,b) = \
| a+b
<function> : ( number, number ) -> number
> fn_add (10,20)
30 : number

The function fn_add takes a tuple with 2 numeric values and returns their sum.


Destructuring involves breaking a tuple into individual values. To access individual values in a tuple with three or more elements, we use destructuring. Here, we assign each value in a tuple to different variables. Using _ one can define placeholders for values that will be ignored or skipped.


> (first,_,_) = (10,20,30)
10 : number
> first
10 : number


In this example, we wil use let..in block syntax to destructure. The let block contains the variables and the in block contains expressions that should be evaluated and value that should be returned.

> t1 = (10,20,30)
(10,20,30) : ( number, number1, number2 )
> let \
(a,b,c) = t1 \
a + b +c
60 : number

We are declaring variables a b c in let clause and accessing them using in clause.

Kickstart Your Career

Get certified by completing the course

Get Started