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: Erick Tryzelaar <erickt@d...>
Subject: Re: [Caml-list] generic Hashtbl.to_array
Christoph Bauer wrote:
> Hi,
>
> what is the best way to write Hashtbl.to_array?
>
> Hashtbl.to_array : ('a, 'b) Hashtbl.t -> ('a * 'b) array
>
> The simples idea has the problem, that you don't have
> a initial value to make the result array:

The easiest is to use a temporary list:

# let x = Hashtbl.create 2;;
val x : ('_a, '_b) Hashtbl.t = <abstr>
# Hashtbl.add x 5 3;;
- : unit = ()
# Hashtbl.add x 7 2;;
- : unit = ()
# Array.of_list (Hashtbl.fold (fun a b c -> (a, b) :: c) x []);;
- : (int * int) array = [|(7, 2); (5, 3)|]


You could also try inverting the Hashtbl fold into an iterator+closure 
and pass the closure into the Array.init function, but I'm not sure how 
complicated/efficient that would be.

I suppose it just depends on how efficient you need it to be. If it's 
just some simple stuff, I'd just use the intermediary list.

-e