English version
Accueil     Ŕ propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis ŕ jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml ŕ l'adresse ocaml.org.

Browse thread
Weak hash table for attaching extra data to an object
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2007-08-14 (11:08)
From: Thomas Fischbacher <tf@f...>
Subject: Re: [Caml-list] Weak hash table for attaching extra data to an object

Richard Jones wrote:

> I have a module which I can't edit[1].  This module, let's call it
> Document, stores a representation of an XML tree in internal node
> objects:
>   type intnode
> What I want to do is -- completely outside Document -- attach my own
> extra information to these nodes. 

Ah, so the situation really is somewhat common, and not something
just I am running into occasionally. (The problem in particular
also arises occasionally when writing symbolic algebra code when one
wants to attach meta-data (e.g. on typesetting) to terms without
touching the underlying term representations in any way.)

> The key point is that if the
> garbage collector collects an intnode, then I want my extra
> information to be garbage collected too.
> I wonder if anyone has done this, or can suggest a better way to solve
> this problem?  The issue of attaching extra data to some existing
> object would seem to be a fairly common one ...

You might be able to "fake" a weak hash table by using a trick: for a
key-value entry k1 -> v1, you take k1 and v1 and rebuild the outermost
data structure to get k2 with k2 = k1 and k2 != k1 (oh hey, now that
looks confusing, right?), as well as v2 = v1 and v2 != v1. Now, you
enter k2 -> v2 into an ordinary hash table and register finalizers for
k1 and v1 which remove this k2 -> v2 entry from your hash. That might

best regards,
Thomas Fischbacher