Haskell:在列表中的每个元组中调用另一个函数

时间:2018-02-12 21:42:15

标签: dictionary haskell

我有一个元组的一般列表,如Map.fromList [(10,20),(30,40),(50,60)]

-- takes list of tuples and produce another list of tuples  
GeneralFunction ::Ord m -> [(m,m)] -> Map m [m] -> Map m [m]

-- takes a tuple (x,y) and produce [(x,y),(y,x)] for each tuple in the general list 
specialFunction ::Ord m -> (m,m) -> Map m [m]

我有一个generalFunction,我想调用一个特殊的函数,它接受一个元组(x,y)并插入(x,y)(y,x)为一般列表的每个元组,具体取决于它长度

例如:当我使用GeneralFunction致电Map.fromList [(10,20),(30,40),(50,60)]时 最终结果将如此Map.fromList [(10,20),(20,10),(30,40),(40,30),(50,60),(60,50)]

我知道如何使用insertWith键值以及如何使用list。

问题:

我更依赖于通过元组迭代元组的过程

欢迎任何迹象,想法或提示。

1 个答案:

答案 0 :(得分:2)

您可以做的是将Map放在specialFunction中,并考虑它们是否仅仅是元组列表:

specialFunction :: Ord m -> (m, m) -> [(m, m)]
specialFunction (a, b) = [(a, b), (b, a)]

然后,我不太确定你的generalFunction做了什么,但你可以同样使用specialFunction

generalFunction :: Ord m -> [(m, m)] -> Map m m
generalFunction = Map.fromList . concat . map specialFunction

如果要在值列表上应用某些函数,可以始终使用map(对map数据类型也有Map

因此,你得到:

Prelude Data.Map> generalFunction [(10,20),(30,40),(50,60)]
fromList [(10,20),(20,10),(30,40),(40,30),(50,60),(60,50)]
相关问题