🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Collection Choices

Collection choice is the decision about which container holds a group of values. The right container makes lookups and membership tests easy to read and to trust.

A Map lookup gives the paired value

This Map pairs two names with ages. The lookup and the size are printed, not the Map itself.

import qualified Data.Map as Map
main :: IO ()
main = do
  let scores = Map.fromList [("ana", 31), ("bo", 28)]
  print (Map.lookup "ana" scores)
  print (Map.size scores)

A short list lookup gives the same answer

The same lookup on a short list of pairs gives the same answer. A Map is the better choice once the key count grows.

main :: IO ()
main = do
  let pairs = [("ana", 31), ("bo", 28)]
  print (lookup "ana" pairs)
  print (length pairs)

A Set removes duplicates and sorts values

This Set removes the duplicate 3 and sorts the rest. The sorted list, the size, and the membership test are printed.

import qualified Data.Set as Set
main :: IO ()
main = do
  let xs = Set.fromList [3, 1, 3, 2]
  print (Set.toAscList xs)
  print (Set.size xs)
  print (Set.member 2 xs)

Example

import qualified Data.Map as Map
main :: IO ()
main = do
  let scores = Map.fromList [("lee", 90), ("ana", 85), ("bo", 78)]
  print (Map.toAscList scores)
  print (Map.lookup "lee" scores)
  print (Map.size scores)

Key points

  • List: a sequence of values in order, searched from the front.
  • Map: a container that pairs each key with one value and keeps keys in sorted order.
  • Set: a container that holds each value once and keeps values in sorted order.
  • Use a Map for lookups by key when many keys are involved.
  • Use a Set for membership tests and for removing duplicates.
  • Use a list for a short sequence where order and duplicates both matter.

In this example, the program builds a Map of three scores. It prints the pairs in sorted key order, then the lookup for lee, then the size, so the reader can check the container without seeing the Map value itself.

Note

A Map or Set value is never printed directly in this course, and lookups, sizes, and sorted lists are printed instead.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which container best answers whether a value is present, with each value held once?