unsafePtrCompare, anybody?

Leon Smith lps@po.cwru.edu
Sat, 15 Sep 2001 15:11:02 -0400

I'm writing an atom table for a compiler/interpreter, and it would be really 
nice to use unsafePtrLT to implement tree-based finite maps.  

For clarification, my atom table consists  of these three functions: 

mkAtom :: String -> IO Atom
show  :: Atom -> String
(==)  :: Atom -> Atom -> Bool

such that   
	mkAtom s >>= (return . show) == return s
	mkAtom . show == return
	atom == atom'  <=>  show atom == show atom' 

mkAtom looks up each string in a table stored in an global variable, and 
returns the atom stored in the table if it is there.  Otherwise, it makes the 
string into an atom, inserts the atom into the table, and returns this new 

The point of all of this is that now string equality, when strings are made 
into atoms, is just pointer equality, which is available as 

However, in this situation, pointer comparison is simply an arbitrary total 
order on the set of all atoms, which is all we need to implement finite maps 
based on search trees.  And of course, pointer comparisons are a much cheaper 
operation that actual string comparison.

Of course, the misuses of unsafePtrEq aren't nearly as heinous as those of 
unsafePtrCompare.   On the other hand, it might be next to impossible to 
effectively use unsafePtrCompare in cases that it isn't completely safe to 
use, whereas there are plently of situations where unsafePtrEq is semi-safe 
to use.