[Haskell-cafe] translate imperative pseudo code into haskell

Frerich Raabe raabe at froglogic.com
Fri Aug 9 17:37:37 CEST 2013


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 at froglogic.com
www.froglogic.com - Multi-Platform GUI Testing




More information about the Haskell-Cafe mailing list