You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Returns an arbitrary (i.e. quickest to access) key-value pair in a hashtable, or raises Not_found if the hashtable is empty.
This would be useful for starting a function that finds the key with the maximum value:
let hashmax gt t =
let maxfolder key value (maxkey, maxval) =
if gt key maxkey then
(key, value)
else
(maxkey, maxval)
in
let startpair = Hashtbl.arbitrary t in
Hashtbl.fold maxfolder t startpair
Additional information
The code for such a function might look like:
let arbitrary h =
let d = h.data in
let len = Array.length d
let rec loop i =
if i == len then
raise Not_found
else
(match d.(i) with
Empty -> loop(i+1)
| Cons(key, val, _) -> (key, val))
in
loop 0
The text was updated successfully, but these errors were encountered:
No activity for 10 years. The requested behavior does not seem very common and can be achieved with the current API (Hashtbl.iter + an exception to stop the traversal after the first element). So marking as "won't fix".
Original bug ID: 4103
Reporter: acone
Assigned to: @alainfrisch
Status: resolved (set by @alainfrisch on 2016-12-07T15:50:38Z)
Resolution: won't fix
Priority: normal
Severity: feature
Version: 3.09.2
Category: standard library
Tags: patch
Bug description
Hashtbl.arbitrary : ('a, 'b) Hashtbl.t -> ('a * 'b)
Returns an arbitrary (i.e. quickest to access) key-value pair in a hashtable, or raises Not_found if the hashtable is empty.
This would be useful for starting a function that finds the key with the maximum value:
let hashmax gt t =
let maxfolder key value (maxkey, maxval) =
if gt key maxkey then
(key, value)
else
(maxkey, maxval)
in
let startpair = Hashtbl.arbitrary t in
Hashtbl.fold maxfolder t startpair
Additional information
The code for such a function might look like:
let arbitrary h =
let d = h.data in
let len = Array.length d
let rec loop i =
if i == len then
raise Not_found
else
(match d.(i) with
Empty -> loop(i+1)
| Cons(key, val, _) -> (key, val))
in
loop 0
The text was updated successfully, but these errors were encountered: