[Haskell-cafe] Strange random choice algorithm

Chaddaï Fouché chaddai.fouche at gmail.com
Sun Jan 31 03:53:30 EST 2010


On Sat, Jan 30, 2010 at 9:38 PM, Daniel Fischer
<daniel.is.fischer at web.de> wrote:
>> Also, is there a more direct way of printing an array?
>
> Sure,
>
> printing immutable arrays:
>
> print arr ~> array (lo,hi) [(lo,arr!lo), ... , (hi,arr!hi)]
> print (assocs arr) ~> [(lo,arr!lo), ... , (hi,arr!hi)]
> print (elems arr) ~> [(arr!lo), ... , (arr!hi)]

Those are all fine.

>
> printing IO[U]Arrays:
>
> do immArr <- freeze arr
>   print (immArr :: [U]Array ix el)
>
> do ass <- getAssocs arr
>   print ass
>
> (getAssocs arr >>= print)
>
> do els <- getElems arr
>   print els
>

On the other hand, all those suggestions have a severe efficiency
problem due to the IO Monad strictness, for instance (getAssocs arr
>>= print) will start by creating the whole list of associations
before printing any of it.

More efficient and still better than the initial code would be :

mapM_ (readArray arr >=> print) [1..9]

-- 
Jedaï


More information about the Haskell-Cafe mailing list