TExcelTAD
Home › Haskell › Haskell Data.Map & Data.Set

Haskell Data.Map & Data.Set

Lists are great for sequences, but looking something up in a list means scanning it. For key-value data and membership tests, the containers package (bundled with GHC) provides Data.Map and Data.Set. Both are immutable balanced binary trees: lookups, inserts and deletes take O(log n) time, and keys are kept sorted.

Creating and querying a Map

A Map k v maps keys of type k (which must be Ord) to values of type v. Import it qualified, because many of its names clash with the Prelude:

haskell · try it yourself
import qualified Data.Map.Strict as Map

main :: IO ()
main = do
  let stock = Map.fromList [("apple", 12), ("pear", 0), ("banana", 7)]
  print stock
  print (Map.lookup "banana" stock)
  print (Map.lookup "kiwi" stock)
  print (Map.findWithDefault 0 "kiwi" stock)
  print (Map.member "pear" stock, Map.size stock)
  print (Map.keys stock, Map.elems stock)
fromList [("apple",12),("banana",7),("pear",0)]
Just 7
Nothing
0
(True,3)
(["apple","banana","pear"],[12,7,0])

Map.lookup returns a Maybe, so a missing key is a value you must handle, never a crash. The keys come out sorted, regardless of insertion order.

Note: Data.Map.Strict and Data.Map share the same Map type. The strict module evaluates values as they are inserted, which avoids memory build-up; prefer it unless you specifically need lazy values.

Updating a Map

Every "update" returns a new map; the old one is unchanged. Thanks to structural sharing, this is cheap: only O(log n) nodes are copied.

haskell · try it yourself
import qualified Data.Map.Strict as Map

main :: IO ()
main = do
  let stock = Map.fromList [("apple", 12), ("pear", 0), ("banana", 7)]
      restocked = Map.insert "kiwi" 20 stock          -- add or replace
      sold = Map.adjust (subtract 2) "apple" restocked -- change one value
      cleaned = Map.filter (> 0) sold                  -- drop empty items
      merged = Map.insertWith (+) "banana" 5 cleaned   -- combine with old value
  print restocked
  print sold
  print cleaned
  print merged
  print (Map.delete "kiwi" merged)
  print stock                                          -- the original is untouched
fromList [("apple",12),("banana",7),("kiwi",20),("pear",0)]
fromList [("apple",10),("banana",7),("kiwi",20),("pear",0)]
fromList [("apple",10),("banana",7),("kiwi",20)]
fromList [("apple",10),("banana",12),("kiwi",20)]
fromList [("apple",10),("banana",12)]
fromList [("apple",12),("banana",7),("pear",0)]
Function Purpose
Map.insert k v m add or replace
Map.insertWith f k v m add, or combine f new old if the key exists
Map.adjust f k m apply f to one value (no-op if missing)
Map.alter f k m general: f gets Maybe v, returns Maybe v
Map.delete k m remove a key
Map.map f m, Map.filter p m transform or filter values
Map.unionWith f a b merge two maps
Map.foldrWithKey f z m fold over keys and values
Map.toList m sorted list of pairs

Counting and grouping

Two very common tasks are counting occurrences and grouping items by a key. fromListWith does both in one line:

haskell · try it yourself
import qualified Data.Map.Strict as Map
import Data.Char (toLower, isAlpha)

main :: IO ()
main = do
  let text = "the cat and the hat and the bat"
      counts = Map.fromListWith (+) [(w, 1 :: Int) | w <- words text]
  print counts
  print (Map.toList (Map.filter (> 1) counts))

  let animals = ["cat", "cow", "dog", "duck", "crab"]
      byLetter = Map.fromListWith (flip (++)) [(head a, [a]) | a <- animals]
  print byLetter

  let letters = Map.fromListWith (+) [(toLower c, 1 :: Int) | c <- "Mississippi", isAlpha c]
  mapM_ (\(c, n) -> putStrLn (c : ": " ++ replicate n '#')) (Map.toList letters)
fromList [("and",2),("bat",1),("cat",1),("hat",1),("the",3)]
[("and",2),("the",3)]
fromList [('c',["cat","cow","crab"]),('d',["dog","duck"])]
i: ####
m: #
p: ##
s: ####

flip (++) appends new items at the end, so each group keeps the original order.

Folding over a Map

haskell · try it yourself
import qualified Data.Map.Strict as Map

prices :: Map.Map String Double
prices = Map.fromList [("coffee", 3.5), ("muffin", 2.25), ("juice", 4.0)]

main :: IO ()
main = do
  print (sum prices)                                 -- Map is Foldable over its values
  print (Map.foldrWithKey (\k v acc -> k ++ "=" ++ show v ++ " " ++ acc) "" prices)
  print (Map.lookupMin prices, Map.lookupMax prices)
  print (fmap (* 1.1) (Map.lookup "juice" prices))
9.75
"coffee=3.5 juice=4.0 muffin=2.25 "
(Just ("coffee",3.5),Just ("muffin",2.25))
Just 4.4

Data.Set

A Set a is a collection of unique, sorted values. It is the right choice for membership checks and for set algebra:

haskell · try it yourself
import qualified Data.Set as Set

main :: IO ()
main = do
  let alice = Set.fromList ["rust", "haskell", "sql", "haskell"]
      bob = Set.fromList ["sql", "go", "haskell"]
  print alice
  print (Set.member "go" alice, Set.size alice)
  print (Set.union alice bob)
  print (Set.intersection alice bob)
  print (Set.difference alice bob)
  print (Set.toList (Set.map length bob))
  print (Set.insert "elm" bob)
fromList ["haskell","rust","sql"]
(False,3)
fromList ["go","haskell","rust","sql"]
fromList ["haskell","sql"]
fromList ["rust"]
[2,3,7]
fromList ["elm","go","haskell","sql"]

Tip: nub from Data.List removes duplicates in O(n²) time. For anything larger than a few dozen elements, Set.toList (Set.fromList xs) is far faster (O(n log n)), though it sorts the result.

Test yourself

What does Map.lookup k m return when k is missing?

  1. It crashes
  2. Nothing
  3. An empty string
  4. 0

What is Map.fromListWith (+) [("a", 1), ("b", 1), ("a", 1)]?

  1. fromList [("a",1),("b",1)]
  2. fromList [("a",2),("b",1)]
  3. An error: duplicate key
  4. fromList [("a",1),("b",1),("a",1)]

Why import Data.Map qualified?

  1. It is required by GHC
  2. Its names like filter, map and lookup clash with the Prelude
  3. Qualified imports are faster
  4. To make the keys sorted