# Containers - Data.Map

# Monoid instance

Map k v provides a Monoid (opens new window) instance with the following semantics:

  • mempty is the empty Map, i.e. the same as Map.empty (opens new window)
  • m1 <> m2 is the left-biased union of m1 and m2, i.e. if any key is present both in m1 and m2, then the value from m1 is picked for m1 <> m2. This operation is also available outside the Monoid instance as Map.union (opens new window).

# Constructing

We can create a Map from a list of tuples like this:

A Map can also be constructed with a single value:

There is also the empty function.

Data.Map also supports typical set operations such as union (opens new window), difference (opens new window) and intersection (opens new window).

# Checking If Empty

We use the null function to check if a given Map is empty:

# Finding Values

There are many (opens new window) 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:

notMember is similar:

You can also use findWithDefault :: Ord k => a -> k -> Map k a -> a (opens new window) to yield a default value if the key isn't present:

# Inserting Elements

Inserting (opens new window) elements is simple:

# Deleting Elements

# Importing the Module

The Data.Map module in the containers package (opens new window) 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:

Map.empty -- give me an empty Map