this is what I have for matrix addition in Haskell
> add :: (Num a) => [[a]] -> [[a]] -> [[a]]
> add [] [] = []
> add (x:xs) (y:ys) = zipWith (+) x y : add xs ys
add [[1,2], [3,4]] [[5,6], [7,8]] gives me [[6,8],[10,12]]
However, I am trying do with one line instead
> add :: (Num a) => [[a]] -> [[a]] -> [[a]]
> add = map ((zipWith (+))
How come the map function doesn't work?
The map
function doesn't work here because you're iterating over two lists instead of one. To iterate over two lists in parallel, you use zipWith
, just like you are already doing for the inner loop.
Prelude> let add = zipWith (zipWith (+))
Prelude> add [[1, 2], [3, 4]] [[5, 6], [7, 8]]
[[6,8],[10,12]]
map
takes in a single list: you're trying to give it two.
Try something like:
add = zipWith (zipWith (+))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With