Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Matrix Addition/Subtraction

Tags:

haskell

map

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?

like image 323
nobody Avatar asked Oct 05 '11 01:10

nobody


2 Answers

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]]
like image 107
hammar Avatar answered Oct 03 '22 06:10

hammar


map takes in a single list: you're trying to give it two.

Try something like:

add = zipWith (zipWith (+))
like image 37
ivanm Avatar answered Oct 03 '22 08:10

ivanm