Version française
Home     About     Download     Resources     Contact us    
Browse thread
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: Damien Doligez <damien.doligez@i...>
Subject: Re: [Caml-list] generic Hashtbl.to_array
Hello,

On 2006-07-25, at 10:29, Christoph Bauer wrote:

> The simples idea has the problem, that you don't have
> a initial value to make the result array:

You can get it from the hash table itself:

let to_array t =
   let init = ref None in
   begin try Hashtbl.iter (fun k v -> init := Some (k,v); raise Exit) t
   with Exit -> ()
   end;
   match !init with
   | None -> [| |]
   | Some i ->
     let a = Array.make (Hashtbl.length t) i in
     ignore (Hashtbl.fold (fun k v i -> a.(i) <- (k, v); i + 1) t 0);
     a
;;

-- Damien