Grouping Data with Tuples
Introduction To Tuples
Welcome to Unit 4 out of our 7 units in this course! So far, we have looked at ways to write functions and handle groups of data. You might recall from Lesson 2 that we used lists to group data. However, lists have a strict rule: every item inside a list must be of the same type. You can have a list of numbers or a list of characters, but you cannot mix them.
Sometimes, you need to group related items that are not of the same type. For example, if you want to store a person's name alongside their age, a list will not work. This is where tuples come in. A tuple is a way to group a fixed number of items into a single unit, and these items can be of different types. Think of a tuple as a specific container designed to hold an exact set of values, like a pair. Let's look at how to create and use them.
Creating Tuples And Extracting Values
To create a tuple in Haskell, you place your values inside parentheses and separate them with commas. Let's start by defining a simple pair that holds a person's name as a String and their age as an Int.
Notice the type signature (String, Int). It perfectly matches the shape of our data. We have exactly two values: a String and an Int.
Once you have data grouped in a pair, you need a way to get it back out. Haskell provides two built-in functions specifically for two-item tuples: fst grabs the first item, and snd grabs the second item. Let's write a main function to pull these values out and display them on the screen.
In this code, fst person gives us "Ada". Since "Ada" is a String, we use putStrLn to print it. Then, snd person gives us 36. Because 36 is an Int, print is the simplest choice here.
If you run this code, the output will look like this:
Output:
Returning Multiple Values From A Function
Tuples are extremely useful for solving a common programming challenge. In Haskell, a function can only ever return exactly one value. But what if you need to calculate two different things and return them both? Tuples solve this by wrapping multiple results into a single tuple package.
Let's build a function called minMax that takes two numbers and returns a pair containing both the smaller number and the larger number. First, we will define its type signature and the calculation.
The type signature Int -> Int -> (Int, Int) tells us that the function accepts two integers and returns a pair of integers. Inside the function, we use the built-in min and max functions, placing their results directly inside parentheses to form the tuple (min a b, max a b).
Now, let's add this to our ongoing code and see how it looks when we run it.
When minMax 8 3 is called, it calculates the minimum (3) and maximum (8) and packages them together. We use print to display the entire tuple at once.
Output:
