[Haskell-cafe] Global Arrays

Clark Gaebel cgaebel at csclub.uwaterloo.ca
Fri Mar 9 21:48:59 CET 2012

In Haskell, what's the canonical way of declaring a top-level array
(Data.Vector of a huge list of doubles, in my case)? Performance is
key in my case.

The straightforward way would just be something like:

globalArray :: V.Vector Double
globalArray = V.fromList [ huge list of doubles ]
{-# NOINLINE globalArray #-}

However, I don't want to have to run the fromList at runtime. Not only
would this mean a bigger executable (having to store a linked list,
instead of an array), it would be quite inefficient since we don't
even use the source list!

Therefore, I was thinking of storing the array in a C file:

static const double globalArray[] = { huge list of doubles };
double* getGlobalArray() { return globalArray; }
int        getGlobalArraySize() { return
sizeof(globalArray)/sizeof(globalArray[0]); }

And importing it in haskell witht he FFI, followed with an unsafeCast:

foreign import ccall unsafe "getGlobalArray" c_globalArray :: Ptr CDouble
foreign import ccall unsafe "getGlobalArraySize" c_globalArraySize :: CInt

globalArray :: V.Vector Double
globalArray = V.unsafeCast $ unsafeFromForeignPtr0 (unsafePerformIO $
newForeignPtr_ c_globalArray) (fromIntegral c_globalArraySize)
{-# NOINLINE globalArray #-}

But this version (clearly) is full of "unsafe"ty. Is there a better
way that I haven't thought of?

  - clark

More information about the Haskell-Cafe mailing list