caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
From: Christoph Bauer <christoph.bauer@lms-gmbh.de>
To: caml-list <caml-list@inria.fr>
Subject: generic Hashtbl.to_array
Date: Tue, 25 Jul 2006 10:29:22 +0200	[thread overview]
Message-ID: <26EB47FDD566A7469FC862DAF373792F01711274@kaiserslautern1.lmsintl.com> (raw)

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


             reply	other threads:[~2006-07-25  8:29 UTC|newest]

Thread overview: 4+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2006-07-25  8:29 Christoph Bauer [this message]
2006-07-25  9:14 ` [Caml-list] " Erick Tryzelaar
2006-07-25 11:45 ` Damien Doligez
2006-07-26  2:16 oleg

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=26EB47FDD566A7469FC862DAF373792F01711274@kaiserslautern1.lmsintl.com \
    --to=christoph.bauer@lms-gmbh.de \
    --cc=caml-list@inria.fr \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).