
I would like to create a data structure that uses an unboxed array as one of its components. I would like the data structure to be parameterized over the type of the elements of the array. Further, I'd like to build the array using runSTUArray. I can't make the code work though. My naive approach: data Ring a = Ring (UArray Int a) and the code to make the array: makeArray :: [a] -> Ring a makeArray ls = Ring (ST.runSTUArray (ST.newListArray (0, length ls - 1) ls)) But that doesn't work. I get from GHC (6.8.1): Could not deduce (MArray (STUArray s) a (ST s)) from the context () arising from a use of `newListArray' I am pretty sure I need to constrain 'a' to primitive types only, but how? Can I do it in the data definition? Thanks in advance for any help! Justin

On Sat, Nov 10, 2007 at 11:09:54AM -0800, Justin Bailey wrote:
I would like to create a data structure that uses an unboxed array as one of its components. I would like the data structure to be parameterized over the type of the elements of the array. Further, I'd like to build the array using runSTUArray. I can't make the code work though. My naive approach:
data Ring a = Ring (UArray Int a)
and the code to make the array:
makeArray :: [a] -> Ring a makeArray ls = Ring (ST.runSTUArray (ST.newListArray (0, length ls - 1) ls))
But that doesn't work. I get from GHC (6.8.1):
Could not deduce (MArray (STUArray s) a (ST s)) from the context () arising from a use of `newListArray'
I am pretty sure I need to constrain 'a' to primitive types only, but how? Can I do it in the data definition?
Thanks in advance for any help!
What you're trying to do deliberately can't be done. Polymorphism has a runtime cost in GHC, and UArrays must specialize. That said, have you heard of Data.Array.IArray.listArray? Stefan

Hello Justin, Saturday, November 10, 2007, 10:09:54 PM, you wrote:
makeArray :: [a] -> Ring a makeArray ls = Ring (ST.runSTUArray (ST.newListArray (0, length ls - 1) ls))
unboxed arrays in std library are not polymorphic, look at http://haskell.org/haskellwiki/Library/ArrayRef ps: as Stefan said, you will get very low performance with polymorphic code without 100% inlining -- Best regards, Bulat mailto:Bulat.Ziganshin@gmail.com
participants (3)
-
Bulat Ziganshin
-
Justin Bailey
-
Stefan O'Rear