From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: X-Spam-Checker-Version: SpamAssassin 3.1.3 (2006-06-01) on yquem.inria.fr X-Spam-Level: * X-Spam-Status: No, score=1.5 required=5.0 tests=SPF_SOFTFAIL autolearn=disabled version=3.1.3 X-Original-To: caml-list@yquem.inria.fr Delivered-To: caml-list@yquem.inria.fr Received: from mail2-relais-roc.national.inria.fr (mail2-relais-roc.national.inria.fr [192.134.164.83]) by yquem.inria.fr (Postfix) with ESMTP id D300FBBAF for ; Tue, 5 Aug 2008 14:05:54 +0200 (CEST) X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: AkcBAFnel0ip5TxXo2dsb2JhbACROAEBAQEBAQcFCAcRnEw X-IronPort-AV: E=Sophos;i="4.31,310,1215381600"; d="scan'208";a="13731374" Received: from gateway0.eecs.berkeley.edu ([169.229.60.87]) by mail2-smtp-roc.national.inria.fr with ESMTP/TLS/DHE-RSA-AES256-SHA; 05 Aug 2008 14:05:53 +0200 Received: from [10.0.1.5] (136-152-208-5.VPN.Berkeley.EDU [136.152.208.5]) (authenticated bits=0) by gateway0.EECS.Berkeley.EDU (8.14.3/8.13.5) with ESMTP id m75C5l2p000056 (version=TLSv1/SSLv3 cipher=AES128-SHA bits=128 verify=NOT) for ; Tue, 5 Aug 2008 05:05:50 -0700 (PDT) Mime-Version: 1.0 (Apple Message framework v753.1) Content-Transfer-Encoding: 7bit Message-Id: <94C5D65F-7CA4-48FF-B4AA-E88E82F6C8E1@cs.berkeley.edu> Content-Type: text/plain; charset=US-ASCII; delsp=yes; format=flowed To: caml-list@yquem.inria.fr From: Brighten Godfrey Subject: Getting an element of a hashtable: simple ... or is it? Date: Tue, 5 Aug 2008 05:05:46 -0700 X-Mailer: Apple Mail (2.753.1) X-Spam: no; 0.00; hashtable:01 hashtable:01 iterating:01 hashtbl:01 iter:01 exception:01 exception:01 data:02 match:02 seems:03 element:03 element:03 let:03 let:03 raise:03 Hi, Suppose you are given a data structure, and you want to retrive one element -- any one element. Sounds simple... and it is, if you have a list (List.hd list) or an array (arr.(0)). But how about a hashtable, if we don't know a priori any of the keys in the hashtable? The best way I've thought of so far is to begin iterating through all the hashtable's elements, but then break out with an exception: exception Done let get_one ht = let el = ref None in (try ( Hashtbl.iter (fun i _ -> el := Some i; raise Done) ht; ) with Done -> ()); match !el with None -> raise Not_found | Some x -> x But this seems clumsy. Any better ideas? Thanks, Brighten Godfrey