[英]Haskell - Merge two lists of tuples by first component
I have the following lists of tuples:我有以下元组列表:
List 1:清单 1:
[("key-1", Type1, Type2, Type3), ("key-2", Type1, Type2, Type3)]
List 2:清单 2:
[("key-1", Type4), ("key-2", Type4)]
and I want to merge these tuples by its first component so that the following result is produced:我想通过它的第一个组件合并这些元组,以便产生以下结果:
Result List:结果列表:
[("key-1", Type1, Type2, Type3, Type4), ("key-2", Type1, Type2, Type3, Type4)]
In what way can I create the result list?我可以通过什么方式创建结果列表?
How about using zipWith
:如何使用zipWith
:
main = print $ merge list1 list2
-- [("key-1",0,True,"a string",'a'),("key-2",1,False,"another string",'b')]
merge :: [(a,b,c,d)] -> [(a,e)] -> [(a,b,c,d,e)]
merge = zipWith $ \(a,b,c,d) (_,e) -> (a,b,c,d,e)
list1 = [("key-1", 0, True, "a string"), ("key-2", 1, False, "another string")]
list2 = [("key-1", 'a'), ("key-2", 'b')]
In general case I would go with converting to maps approach:在一般情况下,我会转换为地图方法:
import Data.Map (Map)
import qualified Data.Map as Map
merge :: Ord a => [(a,b,c,d)] -> [(a,e)] -> [(a,b,c,d,e)]
merge left right = let
mleft = Map.fromList $ map (\(k, a,b,c) -> (k, (a,b,c))) left
mright = Map.fromList right
mergeL (a, b, c, d) acc = case Map.lookup a mright of
Nothing -> acc -- can't merge
Just e -> (a, b, c, d, e) : acc
in foldr mergeL [] left
Note this will get rid of keys that are not present in both lists.请注意,这将删除两个列表中都不存在的键。 In case you need to preserve those you can generate entry with some default values for Nothing
case, add similarly looking mergeR
and concatenate two foldr
in result.如果您需要保留那些您可以为Nothing
情况生成具有一些默认值的条目,请添加外观相似的mergeR
并在结果中连接两个foldr
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.