We’ve seen zip, but I don’t think unzip has been mentioned. To me it’s the obvious way to solve this problem.
addPairsPointwise :: [(Int, Int)] -> (Int, Int)
addPairsPointwise xs = (foldl (+) 0 as, foldl (+) 0 bs)
where (as,bs) = unzip xs
addPairsPointwise' xs = addPairsOp xs (0,0)
where addPairsOp ((x,y):xs) (a,b) = addPairsOp xs (a+x, b+y)
addPairsOp [] r = r
One response to “Exercise 5.7”
Another solution:
addPairsPointwise = foldl (\(x1,y1) (x2,y2)-> (x1+x2,y1+y2)) (0,0)
or without lambdas
addPairsPointwise’ = foldl pairAdd (0,0)
where pairAdd (x1,y1) (x2,y2) = (x1+x2,y1+y2)