我有一个 Map k [v] 类型的动态大小的关联列表,如下所示
myList = fromList [(10,[11,12]),(20,[21,22]),(12,[10,11])]
我想像这样根据键插入值
-- insert value 13 in tuple (10,[11,12]) ==> (10,[11,12,13])
我对操作列表越来越熟悉了,但我真的把她堆起来了。当我像这样使用插入时:
--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])]
它不生成 [10,11],而是用 [11] 替换 [10]。
如果我的列表是空的。 myList = fromList Map.empty
我想在我的列表中插入一个元组 (10,11)。我希望结果是这种行为
myList = insert 10 11 Map.empty ==> [(10,[11]),(11,[10]))]
欢迎任何指示、想法或提示。
最佳答案
您可以尝试使用 insertWith
相反:
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])]
至于你的第二个需求,你可以试试这个:
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])]
其工作原理如下:
*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])]
关于dictionary - Haskell:在关联列表中插入或附加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48740383/