Containers - Data.Map
Constructing
We can create a Map from a list of tuples like this:
Map.fromList [("Alex", 31), ("Bob", 22)]A Map can also be constructed with a single value:
> Map.singleton "Alex" 31
fromList [("Alex",31)]There is also the empty function.
empty :: Map k aData.Map also supports typical set operations such as union, difference and intersection.
Checking If Empty
We use the null function to check if a given Map is empty:
> Map.null $ Map.fromList [("Alex", 31), ("Bob", 22)]
False
> Map.null $ Map.empty
TrueFinding Values
There are many querying operations on maps.
member :: Ord k => k -> Map k a -> Bool yields True if the key of type k is in Map k a:
> Map.member "Alex" $ Map.singleton "Alex" 31
True
> Map.member "Jenny" $ Map.empty
FalsenotMember is similar:
> Map.notMember "Alex" $ Map.singleton "Alex" 31
False
> Map.notMember "Jenny" $ Map.empty
TrueYou can also use findWithDefault :: Ord k => a -> k -> Map k a -> a to yield a default value if the key isn’t present:
Map.findWithDefault 'x' 1 (fromList [(5,'a'), (3,'b')]) == 'x'
Map.findWithDefault 'x' 5 (fromList [(5,'a'), (3,'b')]) == 'a'Inserting Elements
Inserting elements is simple:
> let m = Map.singleton "Alex" 31
fromList [("Alex",31)]
> Map.insert "Bob" 99 m
fromList [("Alex",31),("Bob",99)]Deleting Elements
> let m = Map.fromList [("Alex", 31), ("Bob", 99)]
fromList [("Alex",31),("Bob",99)]
> Map.delete "Bob" m
fromList [("Alex",31)]Importing the Module
The Data.Map module in the containers package provides a Map structure that has both strict and lazy implementations.
When using Data.Map, one usually imports it qualified to avoid clashes with functions already defined in Prelude:
import qualified Data.Map as MapSo we’d then prepend Map function calls with Map., e.g.
Map.empty -- give me an empty MapMonoid instance
Map k v provides a https://stackoverflow.com/documentation/haskell/1879/type-classes/7940/monoid#t=201608211304123263501 instance with the following semantics: