Mutable arrays in Haskell 98

José Romildo Malaquias romildo@uber.com.br
Wed, 27 Mar 2002 20:16:44 -0300


On Wed, Mar 27, 2002 at 03:58:46PM +0000, Malcolm Wallace wrote:
> José Romildo Malaquias <romildo@uber.com.br> writes:
> 
> > I would like to use muttable arrays in Haskell 98, with the GHC
> > _and_ NHC98 compilers. By muttable arrays I mean arrays with
> > in-place updates, as with the MArray arrays (which are not
> > Haskell 98 conformant) found in GHC. Is such array implmentation
> > available?
> 
> Both compilers have libraries supporting the `IOArray' type,
> implemented with in-place update, although obviously the operations
> must be threaded through the IO monad.
> 
> module IOExtras		-- called IOExts in ghc
>   ( ... 
>   , IOArray             -- data IOArray ix elt -- mutable arrays
>   , newIOArray          -- :: Ix ix => (ix,ix) -> elt -> IO (IOArray ix elt)
>   , boundsIOArray       -- :: Ix ix => IOArray ix elt -> (ix, ix)
>   , readIOArray         -- :: Ix ix => IOArray ix elt -> ix -> IO elt
>   , writeIOArray        -- :: Ix ix => IOArray ix elt -> ix -> elt -> IO ()
>   , freezeIOArray       -- :: Ix ix => IOArray ix elt -> IO (Array ix elt)
> 
>   , module Ix           -- re-export Ix for the benefit of IOArrays
>     -- instance Eq (IOArray ix elt)
>   )

I am having difficults in defining a map function over an IOArray object.

My attempt was

  mapIOArray :: Ix ix => (a -> b) -> IOArray ix a -> IO (IOArray ix b)
  mapIOArray f v = do w <- newIOArray bounds ????????????
		      mapping w (range bounds)
      where
      bounds = boundsIOArray v
      mapping w (i:is) = do x <- readIOArray v i
			    writeIOArray w i (f x)
			    mapping w is
      mapping w []     = return w

But I do not know what to use to replace the ????????????. Is there
a polymorphic value in Haskell that can be of any type?

Is it indeed possible to have such function without resorting to
another intermediate data structure (like a list)?

Regards,

Romildo
-- 
Prof. José Romildo Malaquias               Departamento de Computação
http://iceb.ufop.br/~romildo       Universidade Federal de Ouro Preto
romildo@iceb.ufop.br                                           Brasil
romildo@uber.com.br