can't write instance Storable

Fergus Henderson fjh@cs.mu.OZ.AU
Fri, 2 Aug 2002 13:17:53 +1000


On 01-Aug-2002, Hal Daume III <hdaume@ISI.EDU> wrote:
> Okay, I'm dumb and can't figure this out.  I'm migrating hMPI from GHC
> 4.08 to GHC 5.04 (fun fun) and am having trouble writing an instance of
> Storable.  The relevant information is:
> 
> > import Foreign.Storable
> > type MPI_Rank_Type = Int
> > newtype MPI_Rank = MPI_Rank MPI_Rank_Type deriving (Eq)
> > 
> > instance Storable MPI_Rank where
> >     sizeOf    (MPI_Rank r) = sizeOf r
> >     alignment (MPI_Rank r) = alignment r
> >     peek addr = do r <- peek addr
> > 		     return (MPI_Rank r)
> >     poke addr (MPI_Rank r) = poke addr r
> 
> which doesn't work [...]
> I have no idea what's wrong.  if i make it "...do (r :: Int) <- ..." it
> complains: [...]
> it's like it doesn't realize that "peek" is part of the class and can be
> overloaded.

The argument type for `peek' has changed from `Addr' (or something like that)
to a parameterized type `Ptr a'.  So the problem is essentially that
your `peek' method takes a parameter of type `Ptr MPI_Rank',
but needs to call `peek' with a parameter of type `Ptr MPI_Rank_Type'.
You need to use `castPtr' to convert between the two pointer types.
I think the following (untested) code should do it:

     peek addr = do r <- peek (castPtr addr)
 		    return (MPI_Rank r)

Likewise for `poke'.

-- 
Fergus Henderson <fjh@cs.mu.oz.au>  |  "I have always known that the pursuit
The University of Melbourne         |  of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh>  |     -- the last words of T. S. Garp.