Map I
A Map is a data structure that represents a lookup table. It is efficient to determine the output for a given input.
A low-tech (inefficient) version of a map is a list of ordered pairs (x,y).
lowtech :: [(Int,String)]
lowtech = [(0,"Zero"), (4,"Four"), (9,"Nine")]
lowfind want = head [ y | (x,y)<-lowtech, x == want]
lowfind_r :: [(Int,String)] -> Int -> Maybe String
lowfind_r [] _ = Nothing
lowfind_r ((x,y):pts) wantx
| x == wantx = Just y
| otherwise = lowfind_r pts wantx
clow = lowfind 4 == "Four"
A high-tech (efficient) map looks like a list of ordered pairs.
hightech :: M.Map Int String
hightech :: M.fromList [(0,"Zero"), (4,"Four"), (9,"Nine")]
highfind want = hightech M.! want
chigh = highfind 4 == "Four"
Important Functions
You can find all of the functions in the Data.Map documentation.
(!): find the value for a key, error if the key is unknown- member
- lookup: produces a Maybe; failed lookups give
Nothing - insert key value map: add a new item to the map connecting key with value.
Exercises
-
(
con) Given a list of String, produce aMapthat connects each string to the number of its position in the list.con :: [String] -> M.Map String Int ex1 = M.fromList [("Apple",1),("Banana",2),("Dragonfruit",3)] c1 = con ["Apple","Banana","Dragonfruit"] == ex1 -
(
findr) Given a Map from String to Int (just like the previous problem) and a list of String, find the total of all of the corresponding ints. You may assume the Map contains each string in the list.findr :: (M.Map String Int) -> [String] -> Int c2 = findr ex1 ["Apple","Apple","Dragonfruit"] == 5 -
(
dirmap) Create a Map that takes in “up” “down” “left” “right” and outputs the unit vector in that direction in the standard math plane.dirmap :: M.Map String (Int,Int) dirmap = undefined -
Given a list of String, output a list of directions. If a string is not in the dirmap, then output (0,0) for that word.
dirs :: [String] -> [(Int,Int)] c4 = dirs ["up","left","grape"] == [(0,1),(-1,0),(0,0)] -
Given a Map, a String, and an Int n, add the mapping from the string to (n,n)
dmap :: (M.Map String (Int,Int)) -> String -> Int -> (M.Map String (Int,Int)) c5 = dmap dirs "DiagJump" 3 == M.fromList [("DiagJump",(3,3)), ...]