Exercise 5.7

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”

  1. 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)

Leave a Reply

Your email address will not be published. Required fields are marked *