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?
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:
Add an extra base case for one-row matrices. If there's only one row, the result should be just that row, right?
lstsAdder [] = []
lstsAdder [r] = r
lstsAdder (x:xs) = zipWith (+) x $ lstsAdder xs
Fill missing elements with zeroes in the zipping step.
lstsAdder [] = []
lstsAdder (x:xs) = x ^+^ lstsAdder xs
infixrl 6 ^+^
(^+^) :: [a] -> [a] -> [a]
xs^+^[] = xs
[]^+^ys = ys
(x:xs)^+^(y:ys) = (x+y) : (xs^+^ys)
Give an infinite list of zeroes for the base case:
lstsAdder [] = repeat 0
lstsAdder (x:xs) = zipWith (+) x $ lstsAdder xs