Unboxed Vectors of newtype'd values

Ben Gamari bgamari.foss at gmail.com
Wed May 30 06:27:23 CEST 2012

One of the reasons I find Haskell so well suited to my work is its
ability to easily work with large quantities of data. In particular, I
find myself using Data.Vector.Unbox quite frequently.

Another of my reasons for using Haskell is the type safety it
provides. I find myself using newtypes very frequently to force myself
to think about invariants that a more weakly typed language would allow
me to simply ignore.

Sadly, these two features don't interact particularly well. While the
Data.Vector.Unbox documentation claims that "Implementing unboxed
vectors for new data types can be very easy", it then goes on to list an
abridged version of the Complex instance---dozens of lines of
code. While this code certainly isn't difficult to write, it is time
consuming, error-prone, and, above else, utterly mind deadeningly dull
(making it quite uncharacteristic for Haskell). So dull that I generally
avoid newtypes at all cost in code that might need to use unboxed
vectors. This boilerplate is largely due to Vector's use of type
families as this precludes the use of (the otherwise quite cunning)
GeneralizedNewtypeDeriving to automatically derive the necessary

What can be done to fix this unfortunate state of affairs? The obvious
solution here seems to be Template Haskell, but this seems a bit of an
unfortunate hack around what might be a deficiency in the type families
mechanism (or at least this application of it). The newtype package
provides a nice mechanism to pack and unpack newtypes, but providing
blanket Unbox instances for Newtype instances seems like an awful idea
(and, frankly, I'm not sure how this would work with type
families). Other than these two possibilities I am at a loss. Thoughts?
I'd appreciate any ideas folks could offer.


- Ben

More information about the Libraries mailing list