HASKELL / CHAPTER 12
Persistent maps and explicit lookup failure
AdvancedChoose keyed structures with predictable update semantics.
By the end of this chapter
- Use lookup without partial indexing
- Combine duplicate values deliberately
- Explain persistent updates and key ordering
The idea
Data.Map provides an ordered keyed structure rather than a list scanned for every lookup. Lookup returns Maybe, making missing keys visible without a partial indexing exception. Persistent updates return a new map while the old value remains available, so callers can reason about before and after states without mutation. Keys require an ordering instance consistent with their intended identity.
When several records share a key, choose whether later values replace earlier ones or combine them. InsertWith takes a combining function for the new and old values; argument order matters for noncommutative operations. Use qualified imports to keep map operations distinct from list functions. Test duplicate keys and missing keys, and do not confuse key-sorted traversal with first-occurrence insertion order.
import qualified Data.Map.Strict as M
main = do
let old = M.fromList [("a",2 :: Int)]
new = M.insertWith (+) "a" 3 old
print (M.lookup "a" new)
print (M.lookup "a" old)
print (M.lookup "x" new)Just 5 Just 2 Nothing
The new map combines three with two, while the persistent old map retains its original binding.
Try it yourself
Count words with a map while preserving a separately specified reporting order.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING