["Simon Marlow" <simonmar@microsoft.com>] RE: cvs commit: fptools/libraries/base/Foreign ForeignPtr.hs

Alastair Reid alastair at reid-consulting-uk.ltd.uk
Thu Nov 7 17:10:10 EST 2002

> perhaps ForeignPtr should not be an instance of Eq so people can
> provide their own?

Note that if we did this, we'd want to consider adding an operation

  eqForeignPtr :: FP a -> FP a -> Bool 

                          FP b    -- possible variant but not very useful

which lets people test equality of the container and not the contents.

In fact the more I think on it, the more convinced I am that the Eq
instance should compare contaner equality and not contents equality.
The reason is that I believe Eq instances should follow the following
design rule:

     Eq instances should compute observational equivalence

I believe this is satisfied by all Haskell98 types, all the usual
extensions (IORefs and friends) and by derived instances of datatypes.

Just to be clear what I mean by observational equivalence, consider
comparing two IORefs x and y using this code:

    eq x y = do
      a <- readIORef x
      writeIORef (a+1)
      b <- readIORef x
      return (x==y)
  Obviously, this code is a bad way to test if two IORefs are the same
  IORef but the point is that we can observe the difference between
  them.  Similarily, with ForeignPtrs, adding a finalizer to one and not
  the other and then watching for when the finalizer runs is a way that
  we might observe differences between two FPs.
What I don't mean by observational (in)equivalence is this:

  One might be able to distinguish two data structures of type [Int]
  (say), by observing how much memory they consume.

This is perfectly true but Haskell semantics doesn't let you observe
this so we'll rule any such 'observations' as irrelevant or invalid.


ps Careful reading will reveal that I still haven't proposed a
concrete use for eqForeignPtr.  So far, I'm relying on a combination
of gut instinct and the fact that we (i.e., me plus one or more of my
coauthors at the time (Simon PJ, John Peterson, and Simon Marlow)) did
consciously decide to use one semantics instead of the other when we
designed MallocPtrs/ForeignObjs/ForeignPtrs originally.  I thought
about it a good deal harder when I added them than I claim to have
thought about them in the last couple of days.

More information about the FFI mailing list