[Haskell-cafe] translate imperative pseudo code into haskell

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


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




More information about the Haskell-Cafe mailing list