haskellrecursionmatrixzipwith

Recursive sum columns of matrix to single row (with zipWith (+))


lstsAdder :: [[Integer]] -> [Integer]
lstsAdder [] = []
lstsAdder (x:xs) = zipWith (+) x (lstsAdder xs)

As the title says, I want it to recursively add this: [[a,b,c],[d,e,f]] like this: [a+d,b+e,c+f], and this with lists of lists of any finite length. But all my implementation returns is []. Why is that, and how do I fix it?


Solution

  • Your base case is too basic... the function will recursively consume all rows. When it's all the way down the recursion stack, it's left with the empty list, i.e. the list with no rows. This returns an empty result.

    But then, going back the recursion stack, each layer is supposed to be zipped onto it with +. Well, but zipping any list with an empty list results in an empty list!

    There are three ways you can adress this issue: