Reputation: 993
What would be a proper way of working with a map of maps in Haskell? Assuming that I want to have something like
import qualified Data.Map as M
type Key1 = String
type MyMap1 = M.Map Key1 Int
type Key = String
type MyMap = M.Map Key MyMap1
how am I supposed to implement the function which adds elements into the map? The best I can think of is
addE :: Key -> Key1 -> Int -> MyMap -> MyMap
addE k k1 v = M.insertWith M.union k (M.singleton k1 v)
but M.union
gives me O(n) complexity instead of expected O(log n)
Is there a better way to do this or another data structure that should be used instead?
Upvotes: 2
Views: 252
Reputation: 198211
addE :: Key -> Key1 -> Int -> MyMap -> MyMap
addE k k1 v = M.alter (Just . M.insert k1 v . fromMaybe M.empty) k
Upvotes: 3