Learn/Haskell/7. Lists, tuples and lookups
Lesson 7 of 8
Sign in

Haskell, lesson 7

Lists, tuples and lookups

The list is Haskell's everyday collection. All items in a list have the same type, and, like everything in Haskell, a list never changes: functions take a list and return a new one.

Building and taking apart lists

[Int] means "a list of Int". The : operator (called cons) puts an item in front of a list, and ++ joins two lists. Under the hood, [70, 85, 92] is just 70 : 85 : 92 : [].

That structure is what you pattern match on. A list is either empty, [], or an item in front of the rest, (x : rest):

2 exercises to try what you just read.

Exercise 1

Score stats

Press Ctrl Enter or Check to test your code.

Exercise 2

Shopping list

Press Ctrl Enter or Check to test your code.

Prefer pattern matching over head and tail. Those two crash on an empty list, and GHC warns you when you use them.

Everyday list functions

sort lives in the Data.List module, which ships with GHC: add import Data.List (sort) at the top of the file.

map, filter and folds

These three replace most loops:

A fold walks the list and combines items using a function and a starting value. sum is just a fold with + and 0. foldl' is the version to use when building up a total from the left over a long list.

unwords joins a list of strings with spaces, and words does the opposite. Together with map show they turn numbers into a line of text: unwords (map show [1, 2, 3]) is "1 2 3".

Tuples

A tuple groups a fixed number of values that can have different types:

fst and snd get the parts of a pair, but pattern matching is usually clearer: let (name, qty) = item.

Association lists: a simple map

A list of pairs works as a small dictionary, called an association list. The Prelude's lookup finds the value for a key. Because the key might be missing, it returns a Maybe: Just value or Nothing.

You handle a Maybe with case, or with maybe 0 id, which turns Nothing into 0. To "update" an entry, build a new list:

Lookups in an association list check every item, so they suit small collections. Larger programs use Data.Map from the containers package; here we stick to the base library.

Further reading

  • Prelude: list functions
  • Data.List
  • A Gentle Introduction to Haskell: Lists and tuples

Read one line of whole-number game scores separated by spaces (at least one score). Print:

Sample input:

Sample output:

Several people added items to a shared shopping list, so the same item can appear more than once. The first line is the number of entries. Each entry line has an item name and a quantity separated by a space. Add up the quantity for each item and print one line per item, <item>: <total>, in alphabetical order.

Sample input:

Sample output:

The starter parses the entries into a list of pairs. Write addItem, which adds one entry to an association list of totals, then fold it over the entries. sort on a list of pairs sorts by the first item of each pair.

scores :: [Int]
scores = [70, 85, 92]
describeList :: [Int] -> String
describeList []      = "empty"
describeList [x]     = "just " ++ show x
describeList (x : _) = "starts with " ++ show x
length [4, 12, 7]          -- 3
sum [4, 12, 7]             -- 23
maximum [4, 12, 7]         -- 12
minimum [4, 12, 7]         -- 4
reverse [1, 2, 3]          -- [3,2,1]
elem 7 [4, 12, 7]          -- True
take 2 [4, 12, 7]          -- [4,12]
[4, 12, 7] !! 1            -- 12  (index from 0; crashes if out of range)
map (* 2) [4, 12, 7]         -- [8,24,14]   apply to every item
filter (> 5) [4, 12, 7]      -- [12,7]      keep items that pass a test
foldr (+) 0 [4, 12, 7]       -- 23          combine all items into one value
item :: (String, Int)
item = ("milk", 2)
stock :: [(String, Int)]
stock = [("apple", 5), ("pear", 2)]

lookup "apple" stock   -- Just 5
lookup "kiwi" stock    -- Nothing
addStock :: String -> Int -> [(String, Int)] -> [(String, Int)]
addStock key n [] = [(key, n)]
addStock key n ((k, v) : rest)
  | k == key  = (k, v + n) : rest
  | otherwise = (k, v) : addStock key n rest
Count: <how many>
Highest: <max>
Lowest: <min>
Sorted: <scores from low to high, separated by spaces>
70 92 85 64
Count: 4
Highest: 92
Lowest: 64
Sorted: 64 70 85 92
4
milk 2
eggs 12
milk 1
bread 1
bread: 1
eggs: 12
milk: 3