Haskell Tuples
A tuple is a fixed-size collection that groups values of possibly different types. A pair holds two values and a triple holds three values.
A pair can mix types
This pair groups a number with a piece of text.
main :: IO ()
main = print (7, "seven")fst takes the first value and snd the second
The two results are fst and then snd of the same pair, in that order.
main :: IO ()
main = print [fst (30, 12), snd (30, 12)]A triple groups three values
This triple groups a name, an age, and a Bool value.
main :: IO ()
main = print ("Ana", 31, True)A tuple pattern names both parts at once
The equation for addPair names the two parts of its pair x and y.
addPair (x, y) = x + y
main :: IO ()
main = print (addPair (3, 4))Example
label (item, price) = item ++ " costs " ++ price
main :: IO ()
main = putStrLn (label ("Pen", "$3"))Key points
- Pair: a pair is a tuple with two values, written inside parentheses.
- Triple: a triple is a tuple with three values, written inside parentheses.
- Mixed types: the values in a tuple can have different types, unlike the values in a list.
- First of a pair: fst gives the first value of a pair.
- Second of a pair: snd gives the second value of a pair.
- Pair-only helpers: fst and snd work on pairs, not on triples.
- Tuple pattern: a function equation can name the parts of a tuple, as in the pattern (name, score).
In this example, the pattern (item, price) names the two parts of the pair ("Pen", "$3"). The function joins item, the word costs, and price with ++, and putStrLn prints the finished text.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What is the value of snd ("left", 99)?