I have an associative list with dynamic size of type Map k [v] like this
myList = fromList [(10,[11,12]),(20,[21,22]),(12,[10,11])]
in which I want to insert values depending on the key like so
-- insert value 13 in tuple (10,[11,12]) ==> (10,[11,12,13])
I'm getting more familiar with manipulation list but I'm really stack her. When I use insert like this :
--insert value 11 where key equals to 12
insert 12 [11] (fromList [(10,[11,12]),(11,[10,12]),(12,[10])]) == fromList [(10,[11,12]),(11,[10,12]),(12,[11])]
It does not produce [10,11] but rather replace [10] by [11].
And if my list is empty. myList = fromList Map.emptyand I want to insert a tuple (10,11) to my list. I want to expect this behavior as a result
myList = insert 10 11 Map.empty ==> [(10,[11]),(11,[10]))]
Any indications, ideas or hints are welcomed.
You can try using insertWith instead:
Prelude Data.Map> let myList = fromList [(10,[11,12]),(11,[10,12]),(12,[10])]
Prelude Data.Map> insertWith (++) 12 [11] myList
fromList [(10,[11,12]),(11,[10,12]),(12,[11,10])]
As for your second requirement, you can try this:
import Prelude hiding (null)
import Data.Map
insertEmpty :: Int -> Int -> Map Int [Int] -> Map Int [Int]
insertEmpty x y hmap
-- If map is empty, return the paired tuples
| null hmap = pairs
-- If the map is the same as pairs, return it unchanged
| hmap == pairs = hmap
-- Otherwise insert into map
| otherwise = insertWith (++) x [y] hmap
where pairs = fromList [(x, [y]), (y, [x])]
Which works as follows:
*Main> let myList = fromList [(11,[12]),(12,[11])]
*Main> insertEmpty 11 12 myList
fromList [(11,[12]),(12,[11])]
*Main> let myList = fromList []
*Main> insertEmpty 11 12 myList
fromList [(11,[12]),(12,[11])]
*Main> let myList = fromList [(10,[11,12]),(11,[10,12]),(12,[10])]
*Main> insertEmpty 11 12 myList
fromList [(10,[11,12]),(11,[12,10,12]),(12,[10])]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With