Haskell Tuples
A tuple groups a fixed number of values that may have different types. Where a list is "any number of things of one type", a tuple is "exactly these things, of these types". Tuples are written with parentheses and commas.
main :: IO ()
main = do
let point = (3, 4) :: (Int, Int)
person = ("Margaret", 1936, True) :: (String, Int, Bool)
print point
print person
print (fst point, snd point)(3,4)
("Margaret",1936,True)
(3,4)
Lists versus tuples
| List | Tuple | |
|---|---|---|
| Syntax | [1, 2, 3] |
(1, "two", 3.0) |
| Length | Any, can change from list to list | Fixed, part of the type |
| Element types | All the same | Can differ |
| Type | [Int] |
(Int, String, Double) |
| Typical use | A collection to loop over | Returning several values, a key with its value |
The size is part of the type: (Int, Int) and (Int, Int, Int) are different types, so you can't put a pair and a triple in the same list. There is no one-element tuple, and the zero-element tuple is (), the unit type you met with main :: IO ().
Pairs: fst, snd, zip and unzip
Pairs (two-element tuples) are by far the most common. The Prelude has helpers for them:
main :: IO ()
main = do
let cities = ["Hanoi", "Lima", "Oslo"]
populations = [8.4, 10.1, 0.7]
table = zip cities populations
print table
print (map fst table)
print (unzip table)
print (lookup "Lima" table)
print (lookup "Rome" table)[("Hanoi",8.4),("Lima",10.1),("Oslo",0.7)]
["Hanoi","Lima","Oslo"]
(["Hanoi","Lima","Oslo"],[8.4,10.1,0.7])
Just 10.1
Nothing
A list of pairs works as a small dictionary (an association list): lookup finds the value for a key and returns Just value or Nothing. For larger data use Data.Map, which is covered later.
Note:
fstandsndonly work on pairs. For triples and larger tuples, use pattern matching, shown next.
Unpacking tuples with patterns
The clearest way to read a tuple's parts is a pattern that names them. Patterns work in function parameters, in let, and in lambdas:
distance :: (Double, Double) -> (Double, Double) -> Double
distance (x1, y1) (x2, y2) = sqrt ((x2 - x1) ^ 2 + (y2 - y1) ^ 2)
describe :: (String, Int, Bool) -> String
describe (name, year, active) =
name ++ " (" ++ show year ++ ")" ++ (if active then " - active" else "")
main :: IO ()
main = do
print (distance (0, 0) (3, 4))
putStrLn (describe ("Haskell", 1990, True))
let (quotient, remainder) = 17 `divMod` 5
print quotient
print remainder5.0
Haskell (1990) - active
3
2
Returning several values
Functions return exactly one value, but that value can be a tuple. divMod above returns the quotient and remainder together. Your own functions can do the same:
stats :: [Double] -> (Double, Double, Double)
stats xs = (minimum xs, maximum xs, sum xs / fromIntegral (length xs))
splitName :: String -> (String, String)
splitName full = (first, drop 1 rest)
where
(first, rest) = break (== ' ') full
main :: IO ()
main = do
let (low, high, mean) = stats [4, 8, 6, 2]
print (low, high, mean)
print (splitName "Barbara Liskov")
print (span even [2, 4, 5, 6])(2.0,8.0,5.0)
("Barbara","Liskov")
([2,4],[5,6])
break p splits a list at the first element where p is true, and span p splits it at the first element where p is false; both return a pair.
Tuples and comparison
Tuples compare lexicographically: first by the first component, then by the second if the first is equal, and so on. That makes sorting by several keys easy:
import Data.List (sort)
main :: IO ()
main = do
print ((1, 'b') < (2, 'a'))
print ((1, 'b') < (1, 'a'))
-- sort by score descending, then name: put the negated score first
let results = [("Lee", 82), ("Kim", 95), ("Ava", 82)]
print (sort [(negate score, name) | (name, score) <- results])
print (maximum [(score, name) | (name, score) <- results])True
False
[(-95,"Kim"),(-82,"Ava"),(-82,"Lee")]
(95,"Kim")
Tip: Tuples are great for short-lived groupings. When a tuple travels through many functions, or has more than three fields, define a record type instead (see Records):
(String, Int, Bool)says much less thanEmployee { name, year, active }.
Test yourself
What is the type of ("ok", 'x', True)?
[String](String, Char, Bool)(String, String, Bool)Tuple String Char Bool
What does lookup 2 [(1, "a"), (2, "b")] return?
"b"Just "b"2Nothing
Which comparison is True?
(2, 'a') < (1, 'z')(1, 'c') < (1, 'b')(1, 'a') < (1, 'b')(3, 'a') < (3, 'a')