* generic Hashtbl.to_array
@ 2006-07-26 2:16 oleg
2006-07-26 9:48 ` [Caml-list] " Damien Doligez
0 siblings, 1 reply; 3+ messages in thread
From: oleg @ 2006-07-26 2:16 UTC (permalink / raw)
To: caml-list
I wonder about the following solution. At least it traverses the
hashtable exactly once (and it does not ignore the result of the
fold).
let to_array9 t =
let Some (a,_) =
Hashtbl.fold (fun k v seed ->
match seed with
Some (a,i) -> a.(i) <- (k,v); Some (a,i+1)
| None -> let a = Array.make (Hashtbl.length t) (k,v) in
Some (a,1))
t None
in a
;;
^ permalink raw reply [flat|nested] 3+ messages in thread
* Re: [Caml-list] generic Hashtbl.to_array
2006-07-26 2:16 generic Hashtbl.to_array oleg
@ 2006-07-26 9:48 ` Damien Doligez
0 siblings, 0 replies; 3+ messages in thread
From: Damien Doligez @ 2006-07-26 9:48 UTC (permalink / raw)
To: caml users
On 2006-07-26, at 04:16, oleg@pobox.com wrote:
> let to_array9 t =
> let Some (a,_) =
> Hashtbl.fold (fun k v seed ->
> match seed with
> Some (a,i) -> a.(i) <- (k,v); Some (a,i+1)
> | None -> let a = Array.make (Hashtbl.length t) (k,v) in
> Some (a,1))
> t None
> in a
> ;;
It fails whenever the hash table is empty, and the compiler
warns you about it. Replace your "let Some (a,_) = ..."
with a pattern-matching and you have a nice solution.
-- Damien
^ permalink raw reply [flat|nested] 3+ messages in thread
* generic Hashtbl.to_array
@ 2006-07-25 8:29 Christoph Bauer
0 siblings, 0 replies; 3+ messages in thread
From: Christoph Bauer @ 2006-07-25 8:29 UTC (permalink / raw)
To: caml-list
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:
let to_array t =
let a = Array.init make (Hashtbl.length t) ?init? in
ignore
(Hashtbl.fold
(fun k v i ->
a.(i) <- (k, v); i + 1)
t 0);
a
The best solution I found is
let to_array t =
let dummy = Array.init 0 (fun _ -> raise Not_found) in
fst
(Hashtbl.fold
(fun k v (a, i) ->
if i = 0 then
let a = Array.make (Hashtbl.length t) (k, v) in
(a, 0)
else (a.(i) <- (k, v); (a, i + 1)))
t (dummy, 0))
Is there a better one?
Thanks,
Christoph Bauer
^ permalink raw reply [flat|nested] 3+ messages in thread
end of thread, other threads:[~2006-07-26 9:48 UTC | newest]
Thread overview: 3+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2006-07-26 2:16 generic Hashtbl.to_array oleg
2006-07-26 9:48 ` [Caml-list] " Damien Doligez
-- strict thread matches above, loose matches on Subject: below --
2006-07-25 8:29 Christoph Bauer
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox