Reading — step 1 of 5
Learn
~1 min readLists and Beyond
For key-value lookup, use Data.Map:
import qualified Data.Map.Strict as Map
ages :: Map.Map String Int
ages = Map.fromList [("Alice", 30), ("Bob", 25)]
Map.lookup "Alice" ages -- Just 30
Map.lookup "Carol" ages -- Nothing
Map.size ages -- 2
Map.insert "Carol" 40 ages -- new map with Carol added
The qualified import + as Map is conventional — Data.Map reuses many Prelude names (map, filter, etc.), so qualifying avoids clashes.
Data.Map is immutable — every "modification" returns a new map. Backed by a balanced binary tree, so operations are O(log n).
Data.Set works similarly for set operations:
import qualified Data.Set as Set
let s = Set.fromList [3, 1, 4, 1, 5] -- {1, 3, 4, 5}
Set.size s -- 4 (deduplicates)
Set.member 4 s -- True
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…