Version française
Home     About     Download     Resources     Contact us    
Browse thread
Getting an element of a hashtable: simple ... or is it?
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Brighten Godfrey <pbg@c...>
Subject: Getting an element of a hashtable: simple ... or is it?
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