Storable instance for Complex

Jed Brown jed at
Sun Feb 17 10:14:22 EST 2008

On 15 Feb 2008, lemming at wrote:
> On Fri, 15 Feb 2008, Jed Brown wrote:
>> I propose that the following instance be added to base:
>> instance (RealFloat a, Storable a) => Storable (Complex a) where
>> sizeOf z    = 2 * sizeOf (realPart z)
>> alignment z = sizeOf (realPart z)
>> peek p = do
>> [r,i] <- peekArray 2 (castPtr p)
>> return (r :+ i)
>> poke p (r :+ i) = pokeArray (castPtr p) [r,i]
>> This instance is binary compatible with C99, C++ and Fortran complex types.
>> It is currently needed by at least two independent packages: hmatrix and
>> fft. Since it is natural for user code to use both of these packages, we
>> need to move the instance to a common location.
> I also need it for signal processing.

In light of the fact that several packages need this instance, I created
a package storable-complex (on Hackage) which has the instance in
Foreign.Storable.Complex.  In the interest of enabling our packages to
play nicely *now*, I would like to encourage everyone needing this
instance to get it from this common source.  When it (hopefully) makes
it into base, we can use a flag in the .cabal file to get it from base
instead of this package.

Note on style: I decided I agree with Aaron about using explicit
peek/poke rather than a list.  Thus the instance in storable-complex is

  instance (RealFloat a, Storable a) => Storable (Complex a) where
      sizeOf z        = 2 * sizeOf (realPart z)
      alignment z     = sizeOf (realPart z)
      peek p          = do let q = castPtr p
                           r <- peek q
                           i <- peekElemOff q 1
                           return (r :+ i)
      poke p (r :+ i) = do let q = (castPtr p)
                           poke q r
                           pokeElemOff q 1 i

Is Storable/Complex really a special case, or are there other cases
where equivalent instances are defined in different packages?  If so,
would a language extension allowing the user (importing the same
instance from multiple sources) to specify that the instances are
actually identical be helpful?

-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
Url :

More information about the Libraries mailing list