Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Caml-list] Hashtbl and destructive operations on keys
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Remi Vanicat <remi.vanicat@l...>
Subject: Re: [Caml-list] Hashtbl and destructive operations on keys
Thomas Fischbacher <Thomas.Fischbacher@Physik.Uni-Muenchen.DE> writes:

> Dear ocaml hackers,
>
> I read the documentation in such a way that I must not assume that after
> doing a Hashtbl.replace hash key new_val, I can destructively modify key
> with impunity. (I do cons a new key at every Hashtbl.add.)
>
> On the other hand (I have not looked into the sources), I am quite 
> confident that the system _could_ give me the guarantee that 
> nothing evil happens if I do so, and especially for the application I am 
> presently working on, this would induce a noticeable performance gain,
> due to reduced consing. (And performance is important here!)
>
> So, could I please get this officially sanctioned? :-)

This is not an official answers, but it is what ocaml tell me :

# let tbl = create 10;;
val tbl : ('_a, '_b) Hashtbl.t = <abstr>
# let r = ref 10;;
val r : int ref = {contents = 10}
# replace tbl r 50;;
- : unit = ()
# r := 1;;
- : unit = ()
# find tbl r;;
Exception: Not_found.

So no, you can't modify in place the key without a danger. But :

# class myref (x:int) =
  object
     val mutable value = x
     method set n = value <- n
     method get = value
  end;;
class myref :
  int ->
  object
    val mutable value : int
    method get : int
    method set : int -> unit
  end
# let tbl = create 10;;
val tbl : ('_a, '_b) Hashtbl.t = <abstr>
# let r = new myref 10;;
val r : myref = <obj>
# replace tbl r 50;;
- : unit = ()
# r #set 1;;
- : unit = ()
# find tbl r;;
- : int = 50

It do work for object because the hash value of object depend on an
identifier that each object do have, and only of it. Two different
object (even with same field) have a different id, and a object never
change of id. The id can be none by using Oo.id.

-- 
Rémi Vanicat

-------------------
To unsubscribe, mail caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners