Tuple

A tuple is a sequence of values. The values can be any type, and they are indexed by integer, so tuples are not like lists. Tuples are immutable which means you cannot add more elements to the tuple as the program runs.

Tuple vs List in Haskell :

  • Tuple is fixed in size so we cannot alter it, but List can grow as elements gets added.
  • The elements of a tuple do not need to be all of the same type, but list stores only same type of values.

Tuples are marked by parentheses with elements delimited by commas. Let's look at some sample tuples:


(True, 1, False)
("Hello Mars", False)
(9, 5, "Two", False, 'b')

The first example is a tuple containing two elements: True and 1 which are Boolean and number respectively. The next example again has two elements: "Hello Mars"(String) and False (Boolean).

The third example is a tuple consisting of five elements: 9 (a number), 5 (another number), "Two" (a string), False (a boolean value), and 'b' (a character). From this itself you can conclude that tuple accepts all kind of type in a single tuple.

Tuples are useful when you want to return more than one value from a function. In many languages, returning two or more things at once often requires wrapping them up in a single-purpose data structure, maybe one that only gets used in that function. In Haskell, we would return such results as a tuple.

Tuples within tuples

We can store tuples inside other tuples just like normal elements. We can also have tuple of lists, In complex cases we can have combinations of all type in tuples. Fo example, tuple containing a Tuple, List, Boolean, number so on.


((2,3), False)
((4,3), [2,6], True, 9) // tuple with different kinds
[(7,2), (1,4), (9,2)] //list of tuples
[1,6], [2,8], [3,6]] // tuple of lists

Most of the time the Tuple are in pair, so there are less method present for tuple.

Retrieving values :

We can retrieve the first and second values using the fst and snd functions


Prelude> fst (2, 5)
2
Prelude> fst (True, "boo")
True
Prelude> snd (5, "Hello")
"Hello"

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Protractor Online Training : I am starting online training course for Protractor with Typescript from 15th November 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn then you can join the course by sending email to chercher.tech@gmail.com

or Register below


Subscribe
 
Join My Facebook Group
Join Group