[Arrays] Random Access Times ?

Hal Daume III hdaume@ISI.EDU
Mon, 5 May 2003 12:06:09 -0700 (PDT)


Liek I said, you should be able to use IOArrays just as you want:

moussor:Trials/ cat UseArr.hs
import Data.Array.IO

data Foo = Foo Int Int
         deriving (Show)

foo n = do
  (arr :: IOArray Int Foo) <- newArray (1,n) (Foo 0 0)
  mapM_ (\i -> writeArray arr i (Foo i (n-i))) [1..n]
  readArray arr (n-1)

main = do
  v <- foo 1000
  print v
moussor:Trials/ ghc -fglasgow-exts UseArr.hs -o useArr
moussor:Trials/ ./useArr
Foo 999 1


However, if you want to use unboxed arrays, you need to do something like:

instance MArray IOUArray Foo IO where
    unsafeRead (arr :: IOUArray i Foo) i = do
      (arr2 :: IOUArray i Int) <- castIOUArray arr
      v1 <- unsafeRead arr2 (i*2)
      v2 <- unsafeRead arr2 (i*2+1)
      return (Foo v1 v2)


I leave the newArray_ and unsafeWrite functions as exercises
:).  basically in newArray you want to allocate twice as much space as an
int would take (using caseIOUArray) and unsafeWrite is trivial given this
unsafeRead.

that said, you should probably just use IOArrays until you notice that
they're too slow, then figure out how to do this trickery.

--
 Hal Daume III                                   | hdaume@isi.edu
 "Arrest this man, he talks in maths."           | www.isi.edu/~hdaume

On Mon, 5 May 2003, Ron de Bruijn wrote:

> 
> --- Hal Daume III <hdaume@ISI.EDU> wrote:
> > > The one is use is a unboxed and you mean I should
> > > import the Hugslibrary IOExts, just like in my
> > code ,
> > > right?
> > 
> > if you're using arrays of complex values like your
> > data type, i seriously
> > doubt you're using unboxed arrays.  you will have to
> > write special
> > instance methods for them.  and yes, you should just
> > be able to use it as
> > is.
> > 
> 
> I really don't have any idea about how to create an
> instance of that IOArray. The only thing I know about
> this instance is: instance IOArray bounds myDataType
> where, but that's nog enough.
> 
> Can you (again) help me? 
> 
> 
> 
> 
> 
> 
> __________________________________
> Do you Yahoo!?
> The New Yahoo! Search - Faster. Easier. Bingo.
> http://search.yahoo.com
>