translate imperative pseudo code into haskell

I would need some help to get to a reasonable function involving the DB read, addition and multiplication. for 0 <= i < row dimension of A for 0 <= j < column dimension of B for 0 <= k < column dimension of A = row dimension of B sum += (read A (i,k))* (read B(k,j)) I started like this but then somehow lost the compass: main = do map my.read (map (\(x,y) -> "matrixA:" ++ show row ++ ":" ++ show column) [ (i, j, k) | i <- [1..50], j <- [1..20], k <- [1..30] ]) Can you pls help? --Joerg

On 2013-08-09 17:04, Joerg Fritsch wrote:
I would need some help to get to a reasonable function involving the DB read, addition and multiplication.
for 0 <= i < row dimension of A
for 0 <= j < column dimension of B
for 0 <= k < column dimension of A = row dimension of B
sum += (read A (i,k))* (read B(k,j))
I started like this but then somehow lost the compass:
main = do
map my.read (map ((x,y) -> "matrixA:" ++ show row ++ ":" ++ show column) [ (i, j, k) | i <- [1..50], j <- [1..20], k <- [1..30] ])
You could treat lists as monads and write code which looks very much like your pseudo code, something like this -- A few dummy definitions to make 'products' typecheck. data Matrix = Matrix rows :: Matrix -> Int rows = undefined columns :: Matrix -> Int columns = undefined readValue :: Matrix -> (Int, Int) -> Int readValue = undefined -- This is one way to write your pseudo code in Haskell products :: Matrix -> Matrix -> Int products a b = sum $ do i <- [1..rows a] j <- [1..columns b] k <- [1..columns a] return $ readValue a (i, k) * readValue b (k, j) -- Frerich Raabe - raabe@froglogic.com www.froglogic.com - Multi-Platform GUI Testing

On 2013-08-09 17:28, Frerich Raabe wrote:
On 2013-08-09 17:04, Joerg Fritsch wrote:
for 0 <= i < row dimension of A for 0 <= j < column dimension of B for 0 <= k < column dimension of A = row dimension of B sum += (read A (i,k))* (read B(k,j))
[..]
-- This is one way to write your pseudo code in Haskell products :: Matrix -> Matrix -> Int products a b = sum $ do i <- [1..rows a] j <- [1..columns b] k <- [1..columns a] return $ readValue a (i, k) * readValue b (k, j)
It just occurred to me that the ranges of i, j and k are not quite correct, e.g. [1..rows a] should be [0..rows a - 1] to match your pseudo code. That aside, 'products' is probably not a very appropriate name. In any case, you could also keep your approach of building all 3-tuples and then map a function which turns the tuples into products over the list, like: products :: [(Int, Int, Int)] -> [Int] products = map (\i j k -> readA (i, j) * readB (k, j)) ...and then call 'sum' on that. This function actually deserves the name. :-) -- Frerich Raabe - raabe@froglogic.com www.froglogic.com - Multi-Platform GUI Testing
participants (2)
-
Frerich Raabe
-
Joerg Fritsch