Maps in Haskell
Maps are Haskell’s built-in associative data type (similar to hashes or dicts in other languages).
To create an empty map, use the Data.Map.fromList
function:
Set key/value pairs using a similar syntax:
Printing a map with e.g. print
will show all of its key/value pairs.
Get a value for a key with Map.lookup
.
If the key doesn’t exist, the Maybe type will return Nothing
.
The Map.size
function returns the number of key/value pairs when called on a map.
The Map.delete
function removes key/value pairs from a map.
To remove all key/value pairs from a map, create a new empty map.
The Map.member
function checks if a key is present in the map.
You can also declare and initialize a new map in the same line with this syntax:
The Map
module contains a number of useful utility functions for maps.
Note that maps appear in the form fromList [(k,v), (k,v)]
when printed with show
.
To run the Haskell program, save the code in a file named maps.hs
and use runhaskell
or compile it with ghc
.