Version française
Home     About     Download     Resources     Contact us    
Browse thread
AW: [Caml-list] generic Hashtbl.to_array
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Stéphane Glondu <Stephane.Glondu@c...>
Subject: Re: [Caml-list] generic Hashtbl.to_array
I know I am late.

Tom a écrit :
> The dirtiest solution:
> 
> let to_array t =
>  let a =  Array.make (Hashtbl.length t) (Obj.magic 0)  in
>    ignore
>      (Hashtbl.fold (fun k v i -> a.(i) <- (k, v); i + 1) t 0) ;
>      a

What about:

let to_array h =
  let res = ref [||] in
  let rec assign = ref (fun i x ->
			  res := Array.make (Hashtbl.length h) x;
			  !res.(i) <- x;
			  assign := Array.set !res) in
  ignore (Hashtbl.fold (fun k v i -> !assign i (k, v); i+1) h 0);
  !res;;

Sorry if it has already been proposed (but I have not seen it).

-- 
Stéphane Glondu