Ketil Malde Ketil.Malde at bccs.uib.no
Fri Jan 19 03:05:32 EST 2007

```Fernan Bolando wrote:
> what is the simplest way to implement the following code in haskell?
> it's just printing the contents of 2D array.
>
> for(i = 0; i < imax; i++){
>     for(n = 0; n < nmax; n++){
>         printf("%i:%i = %f\n", array[i][n]);
>     }
> }
*%* ghci
___         ___ _
* / _ \ /\  /\/ __(_)
/ /_\// /_/ / /  | |      GHC Interactive, version 6.6, for Haskell 98.
/ /_\\/ __  / /___| |      http://www.haskell.org/ghc/
\____/\/ /_/\____/|_|      Type :? for help.

Prelude>* :m + Data.Array
*Prelude Data.Array>* let a = listArray ((0,0),(2,2)) [1..9]

This is how it looks by default:

*Prelude Data.Array>* a
array ((0,0),(2,2))
[((0,0),1),((0,1),2),((0,2),3),((1,0),4),((1,1),5),((1,2),6),((2,0),7),((2,1),8),((2,2),9)]

'assocs' builds the corresponding assoc list:

*Prelude Data.Array> *assocs a
[((0,0),1),((0,1),2),((0,2),3),((1,0),4),((1,1),5),((1,2),6),((2,0),7),((2,1),8),((2,2),9)]

'map show' converts it into a list of strings:

*Prelude Data.Array>* map show \$ assocs a
["((0,0),1)","((0,1),2)","((0,2),3)","((1,0),4)","((1,1),5)","((1,2),6)","((2,0),7)","((2,1),8)","((2,2),9)"]

'unlines' to convert to a single string where each list element is
one line, and 'putStrLn' to print it:

*Prelude Data.Array> *putStrLn \$ unlines \$ map show \$ assocs a
**((0,0),1)
((0,1),2)
((0,2),3)
((1,0),4)
((1,1),5)
((1,2),6)
((2,0),7)
((2,1),8)
((2,2),9)
*
*To get the exact same output, replace 'show' with a custom-built
function.
*
Prelude Data.Array>* putStrLn \$ unlines \$ map (\((i,j),v)-> show
i++":"++show j++"="++show v) \$ assocs a
0:0=1
0:1=2
0:2=3
1:0=4
1:1=5
1:2=6
2:0=7
2:1=8
2:2=9

```