caml-list - the Caml user's mailing list
 help / color / mirror / Atom feed
* Getting an element of a hashtable: simple ... or is it?
@ 2008-08-05 12:05 Brighten Godfrey
  2008-08-05 12:16 ` [Caml-list] " Richard Jones
                   ` (2 more replies)
  0 siblings, 3 replies; 9+ messages in thread
From: Brighten Godfrey @ 2008-08-05 12:05 UTC (permalink / raw)
  To: caml-list

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


^ permalink raw reply	[flat|nested] 9+ messages in thread

end of thread, other threads:[~2008-08-08 16:02 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2008-08-05 12:05 Getting an element of a hashtable: simple ... or is it? Brighten Godfrey
2008-08-05 12:16 ` [Caml-list] " Richard Jones
2008-08-05 12:26   ` Brighten Godfrey
2008-08-05 12:25 ` blue storm
2008-08-05 21:47   ` Brighten Godfrey
2008-08-08 15:46     ` Ludovic Coquelle
2008-08-08 16:01       ` Peng Zang
2008-08-05 13:21 ` Peng Zang
2008-08-05 21:02   ` Chris Kauffman

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).