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:
import qualified Data.Map as Map
main = do
let m = Map.fromList []
Set key/value pairs using a similar syntax:
let m1 = Map.insert "k1" 7 m
let m2 = Map.insert "k2" 13 m1
Printing a map with e.g. print
will show all of its key/value pairs.
print ("map: " ++ show m2)
Get a value for a key with Map.lookup
.
let v1 = Map.lookup "k1" m2
print ("v1: " ++ show v1)
If the key doesn’t exist, the Maybe type will return Nothing
.
let v3 = Map.lookup "k3" m2
print ("v3: " ++ show v3)
The Map.size
function returns the number of key/value pairs when called on a map.
print ("len: " ++ show (Map.size m2))
The Map.delete
function removes key/value pairs from a map.
let m3 = Map.delete "k2" m2
print ("map: " ++ show m3)
To remove all key/value pairs from a map, create a new empty map.
let m4 = Map.fromList []
print ("map: " ++ show m4)
The Map.member
function checks if a key is present in the map.
let prs = Map.member "k2" m2
print ("prs: " ++ show prs)
You can also declare and initialize a new map in the same line with this syntax:
let n = Map.fromList [("foo", 1), ("bar", 2)]
print ("map: " ++ show n)
The Map
module contains a number of useful utility functions for maps.
let n2 = Map.fromList [("foo", 1), ("bar", 2)]
if n == n2
then print "n == n2"
else return ()
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
.
$ runhaskell maps.hs
map: fromList [("k1",7),("k2",13)]
v1: Just 7
v3: Nothing
len: 2
map: fromList [("k1",7)]
map: fromList []
prs: False
map: fromList [("bar",2),("foo",1)]
n == n2