The Weak
library offers a slight generalisation of
the simple weak pointers described so far:
mkWeak :: k -> v -> Maybe (IO ()) -> IO (Weak v)
mkWeak
takes a key of any type k
and a value of any type
v
, as well as a finalizer, and returns a weak pointer of type
Weak v
.
deRefWeak
returns the value only, not the key, as its
type (given above) implies:
deRefWeak :: Weak a -> IO (Maybe a)
However, deRefWeak
returns Nothing
if the key, not the
value, has died. Furthermore, references from the value to the key
do not keep the key alive, in the same way that the finalizer does
not keep the key alive.
Simple weak pointers are readily defined in terms of these more general weak pointers:
mkWeakPtr :: a -> Maybe (IO ()) -> IO (Weak a)
mkWeakPtr v f = mkWeak v v f
These more general weak pointers are enough to implement memo tables properly.
A weak pointer can be finalized early, using the finalize
operation:
finalize :: Weak v -> IO ()