🎓 A1Learner
🔍
0 of 54 lessons completed

Haskell Maps

A Haskell map is a collection of pairs that links each key to one value. Maps come from the Data.Map module, used here with the short name Map.

Looking a key up in a map

The map links names to scores. A case match unwraps the score stored for Ana.

import qualified Data.Map as Map
scores = Map.fromList [("Ben", 72), ("Ana", 91), ("Cid", 85)]
main :: IO ()
main = do
  case Map.lookup "Ana" scores of
    Just score -> print score
    Nothing -> print 0

insert replaces a value

The insert stores a new score for Ben. The lookup shows 80, and the size stays at 3 pairs.

import qualified Data.Map as Map
scores = Map.fromList [("Ben", 72), ("Ana", 91), ("Cid", 85)]
main :: IO ()
main = do
  let updated = Map.insert "Ben" 80 scores
  case Map.lookup "Ben" updated of
    Just score -> print score
    Nothing -> print 0
  print (Map.size updated)

member, size and toList

The tests check one key and count the pairs. toList gives the pairs in sorted key order.

import qualified Data.Map as Map
scores = Map.fromList [("Ben", 72), ("Ana", 91), ("Cid", 85)]
main :: IO ()
main = do
  print (Map.member "Ana" scores)
  print (Map.size scores)
  print (Map.toList scores)

Example

import qualified Data.Map as Map
scores = Map.fromList [("Ben", 72), ("Ana", 91), ("Cid", 85)]
updated = Map.insert "Dee" 77 scores
main :: IO ()
main = do
  print (Map.size updated)
  print (Map.lookup "Zoe" updated)
  print (Map.toList updated)

Key points

  • Qualified import: maps are used through import qualified Data.Map as Map, so each helper starts with Map and a dot.
  • Map.fromList: a helper that builds a map from a list of key and value pairs.
  • Map.lookup: a helper that gives the value for a key as a Maybe.
  • Map.insert: a helper that adds a pair, or replaces the value when the key is already there.
  • Map.member and Map.size: helpers that say whether a key is present and how many pairs the map holds.
  • Map.toList: a helper that gives the pairs back as a list in sorted key order.

In this example, Map.fromList builds a map of three scores and Map.insert adds a score for Dee. The size is now 4, and the lookup for Zoe gives Nothing since that key is not there. The last line prints the pairs in sorted key order.

Note

a map holds one value per key, so a second pair with the same key replaces the first.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

What does Map.lookup give when the key is not in the map?