2

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?

2
  • Have you tried the update function? Something like addE k k1 v = M.update (Just . M.insert k1 v) should work. Commented Mar 10, 2015 at 18:33
  • 2
    A map of maps is fine, but depending on what you actually do with it, you might want a Map (Key,Key1) Int instead. Commented Mar 10, 2015 at 19:22

1 Answer 1

3
addE :: Key -> Key1 -> Int -> MyMap -> MyMap
addE k k1 v = M.alter (Just . M.insert k1 v . fromMaybe M.empty) k
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.