Storable instance for Complex

Aaron Denney wnoise at ofb.net
Fri Feb 15 16:34:28 EST 2008


On 2008-02-15, Jed Brown <jed at 59A2.org> wrote:
> I propose that the following instance be added to base:
>
>   instance (RealFloat a, Storable a) =3D> Storable (Complex a) where
>       sizeOf z    =3D 2 * sizeOf (realPart z)
>       alignment z =3D sizeOf (realPart z)
>       peek p =3D do
>           [r,i] <- peekArray 2 (castPtr p)
>           return (r :+ i)
>       poke p (r :+ i) =3D pokeArray (castPtr p) [r,i]

I've been using a slightly different instance:

instance (RealFloat a, Storable a) => Storable (Complex a) where
    sizeOf x    = 2 * sizeOf (f x)
    alignment x = alignment  (f x)
    poke      x (a :+ b) = do let y = castPtr x
                              poke y a
                              pokeElemOff y 1 b
    peek      x          = do let y = castPtr x
                              a <- peek y
                              b <- peekElemOff y 1
                              return (a :+ b)

f :: Complex a -> a
f _ = undefined

With a small constant number of elements, I think it makes more sense to
just store them explicitly rather than through a list.

I didn't even think of using realPart, but it makes sense.

-- 
Aaron Denney
-><-



More information about the Libraries mailing list