Haskell:如果 2 个元组的第一个元素相等,则在元组列表中添加第二个元素?

Haskell: add the second elements of 2 tuples if their first elements are equal, in a list of tuples?

示例:

addElement (1, 1) [(1, 1)] = [(1,2)]

addElement (2, 2) [(1,1),(2, 2)] = [(1,1),(2, 4)]

我的代码:

addElement :: (Integer, Integer) -> [(Integer, Integer)]  -> [(Integer, Integer)] 
addElement (a,b) ((x,y):xs)
                         | a==x = ((x,y+b):xs) 
                         |otherwise = addElement ((a+1), b)  xs

我无法让它适用于列表的其余部分。

您需要对函数进行递归,对于 otherwise 的情况产生 (x,y) 二元组。此外,你应该用一个空列表来实现这个案例:

addElement :: (Eq a, Num b) => (a, b) -> [(a, b)]  -> [(a, b)]
addElement _ [] = []
addElement kv@(k1, v1) (kv2@(k2, v2):xs)
    | k1 == k2 = ((k2, v1+v2) : addElement kv xs
    | otherwise = kv2 : addElement kv xs

您可以使用 map 来仅实现适用于单个元素的逻辑,因此:

addElement :: (Eq a, Num b) => (a, b) -> [(a, b)] -> [(a, b)]
addElement (k, v) = map f
    where f kv2@(k2, v2)
              | k == k2 = (k2, v+v2)
              | otherwise = kv2

也可以使用列表理解来完成此操作:

addElem :: (Eq a, Num b) => (a, b) -> [(a, b)] -> [(a, b)]
addElem (x1, x2) lst = [if x1 == y1 then (y1, x2 + y2) else y | y@(y1, y2) <- lst]