Data.Map haskell edit control

I have a map (Map (Int,Int) Int)

(name it Mapp

). I want to create a function mod :: Mapp -> [(Int,Int,Int)] -> Mapp

that for each triple (a, b, c) of given sets of lists Mapp[(a,b)] = c

. How to do it?

+3


source to share


2 answers


mod = foldr (\(a, b, c) -> Map.insert (a, b) c)

      



The idea is very simple: we can insert items from the list one by one using a function fold

.

+1


source


import qualified Data.Map as M

mod :: (Ord k0, Ord k1) => M.Map (k0, k1) a -> [(k0, k1, a)] -> M.Map (k0, k1) a
mod m l = M.fromList (map (\(a,b,c) -> ((a,b),c)) l) `M.union` m

      

Clarification: Take your list l

of threes (a,b,c)

and change them to ((a,b),c)

.

map (\(a,b,c) -> ((a,b),c)) l

      

With a new list, create a new map.



M.fromList (map (\(a,b,c) -> ((a,b),c)) l)

      

Then use M.union

to combine the new map on top and the old one m

:

M.fromList (map (\(a,b,c) -> ((a,b),c)) l) `M.union` m

      

Since it M.union

is left-handed, associations on the left map take precedence over those on the right map, effectively replacing old values ​​with new ones.

0


source







All Articles