dictionary - Haskell:在关联列表中插入或附加值

标签 dictionary haskell

我有一个 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/

相关文章:

ios - 在ios中将带有键的数组添加到字典中

python - 为什么空字典的大小与 Python 中非空字典的大小相同?

haskell - 如何将函数列表中的每个函数应用于 Haskell 一行中的值

haskell -::a -> (a -> b) -> b 运算符 (Haskell)

Travis CI 上的 Haskell 失败,本地通过

python - 如何将字典值转换为 float

python-3.x - 将字典值添加到列表中?

dictionary - Python:获取字典中与key关联的所有值,其中的值可能是一个列表,也可能是单个项

parsing - 'deferred substitution'是什么意思?

haskell - 我如何概括 Maybe 和 Either 的违约行为?