| 1 | (**************************************************************************) |
| 2 | (* *) |
| 3 | (* OCaml *) |
| 4 | (* *) |
| 5 | (* Xavier Leroy, projet Cristal, INRIA Rocquencourt *) |
| 6 | (* *) |
| 7 | (* Copyright 1996 Institut National de Recherche en Informatique et *) |
| 8 | (* en Automatique. *) |
| 9 | (* *) |
| 10 | (* All rights reserved. This file is distributed under the terms of *) |
| 11 | (* the GNU Lesser General Public License version 2.1, with the *) |
| 12 | (* special exception on linking described in the file LICENSE. *) |
| 13 | (* *) |
| 14 | (**************************************************************************) |
| 15 | |
| 16 | (* NOTE: If this file is hashtbl.mli, do not edit it directly! Instead, |
| 17 | edit templates/hashtbl.template.mli and run tools/sync_stdlib_docs *) |
| 18 | |
| 19 | (** Hash tables and hash functions. |
| 20 | |
| 21 | Hash tables are hashed association tables, with in-place modification. |
| 22 | Because most operations on a hash table modify their input, they're |
| 23 | more commonly used in imperative code. The lookup of the value associated |
| 24 | with a key (see {!find}, {!find_opt}) is normally very fast, often faster |
| 25 | than the equivalent lookup in {!Map}. |
| 26 | |
| 27 | The functors {!Make} and {!MakeSeeded} can be used when |
| 28 | performance or flexibility are key. |
| 29 | The user provides custom equality and hash functions for the key type, |
| 30 | and obtains a custom hash table type for this particular type of key. |
| 31 | |
| 32 | {b Warning} a hash table is only as good as the hash function. A bad hash |
| 33 | function will turn the table into a degenerate association list, |
| 34 | with linear time lookup instead of constant time lookup. |
| 35 | |
| 36 | The polymorphic {!t} hash table is useful in simpler cases or |
| 37 | in interactive environments. It uses the polymorphic {!hash} function |
| 38 | defined in the OCaml runtime (at the time of writing, it's SipHash), |
| 39 | as well as the polymorphic equality [(=)]. |
| 40 | |
| 41 | See {{!examples} the examples section}. |
| 42 | *) |
| 43 | |
| 44 | (** {b Unsynchronized accesses} *) |
| 45 | |
| 46 | [@@@warning "-53"] |
| 47 | [@@@alert unsynchronized_access |
| 48 | "Unsynchronized accesses to hash tables are a programming error." |
| 49 | ] |
| 50 | [@@@warning "+53"] |
| 51 | |
| 52 | (** |
| 53 | Unsynchronized accesses to a hash table may lead to an invalid hash table |
| 54 | state. Thus, concurrent accesses to a hash tables must be synchronized |
| 55 | (for instance with a {!Mutex.t}). |
| 56 | *) |
| 57 | |
| 58 | |
| 59 | (** {1 Generic interface} *) |
| 60 | |
| 61 | |
| 62 | type (!'a, !'b) t |
| 63 | (** The type of hash tables from type ['a] to type ['b]. *) |
| 64 | |
| 65 | val create : ?random: (* thwart tools/sync_stdlib_docs *) bool -> |
| 66 | int -> ('a, 'b) t |
| 67 | (** [Hashtbl.create n] creates a new, empty hash table, with initial |
| 68 | size greater or equal to the suggested size [n]. For best results, |
| 69 | [n] should be on the order of the expected number of elements that |
| 70 | will be in the table. The table grows as needed, so [n] is just an |
| 71 | initial guess. If [n] is very small or negative then it is |
| 72 | disregarded and a small default size is used. |
| 73 | |
| 74 | The optional [~random] parameter (a boolean) controls whether |
| 75 | the internal organization of the hash table is randomized at each |
| 76 | execution of [Hashtbl.create] or deterministic over all executions. |
| 77 | |
| 78 | A hash table that is created with [~random] set to [false] uses a |
| 79 | fixed hash function ({!hash}) to distribute keys among |
| 80 | buckets. As a consequence, collisions between keys happen |
| 81 | deterministically. In Web-facing applications or other |
| 82 | security-sensitive applications, the deterministic collision |
| 83 | patterns can be exploited by a malicious user to create a |
| 84 | denial-of-service attack: the attacker sends input crafted to |
| 85 | create many collisions in the table, slowing the application down. |
| 86 | |
| 87 | A hash table that is created with [~random] set to [true] uses the seeded |
| 88 | hash function {!seeded_hash} with a seed that is randomly chosen at hash |
| 89 | table creation time. In effect, the hash function used is randomly |
| 90 | selected among [2^{30}] different hash functions. All these hash |
| 91 | functions have different collision patterns, rendering ineffective the |
| 92 | denial-of-service attack described above. However, because of |
| 93 | randomization, enumerating all elements of the hash table using {!fold} |
| 94 | or {!iter} is no longer deterministic: elements are enumerated in |
| 95 | different orders at different runs of the program. |
| 96 | |
| 97 | If no [~random] parameter is given, hash tables are created |
| 98 | in non-random mode by default. This default can be changed |
| 99 | either programmatically by calling {!randomize} or by |
| 100 | setting the [R] flag in the [OCAMLRUNPARAM] environment variable. |
| 101 | |
| 102 | @before 4.00 the [~random] parameter was not present and all |
| 103 | hash tables were created in non-randomized mode. *) |
| 104 | |
| 105 | val clear : ('a, 'b) t -> unit |
| 106 | (** Empty a hash table. Use [reset] instead of [clear] to shrink the |
| 107 | size of the bucket table to its initial size. *) |
| 108 | |
| 109 | val reset : ('a, 'b) t -> unit |
| 110 | (** Empty a hash table and shrink the size of the bucket table |
| 111 | to its initial size. |
| 112 | @since 4.00 *) |
| 113 | |
| 114 | val copy : ('a, 'b) t -> ('a, 'b) t |
| 115 | (** Return a copy of the given hashtable. *) |
| 116 | |
| 117 | val add : ('a, 'b) t -> key:'a -> data:'b -> unit |
| 118 | (** [Hashtbl.add tbl ~key ~data] adds a binding of [key] to [data] |
| 119 | in table [tbl]. |
| 120 | |
| 121 | {b Warning}: Previous bindings for [key] are not removed, but simply |
| 122 | hidden. That is, after performing {!remove}[ tbl key], |
| 123 | the previous binding for [key], if any, is restored. |
| 124 | (Same behavior as with association lists.) |
| 125 | |
| 126 | If you desire the classic behavior of replacing elements, |
| 127 | see {!replace}. *) |
| 128 | |
| 129 | val find : ('a, 'b) t -> 'a -> 'b |
| 130 | (** [Hashtbl.find tbl x] returns the current binding of [x] in [tbl], |
| 131 | or raises [Not_found] if no such binding exists. *) |
| 132 | |
| 133 | val find_opt : ('a, 'b) t -> 'a -> 'b option |
| 134 | (** [Hashtbl.find_opt tbl x] returns the current binding of [x] in [tbl], |
| 135 | or [None] if no such binding exists. |
| 136 | @since 4.05 *) |
| 137 | |
| 138 | val find_all : ('a, 'b) t -> 'a -> 'b list |
| 139 | (** [Hashtbl.find_all tbl x] returns the list of all data |
| 140 | associated with [x] in [tbl]. |
| 141 | The current binding is returned first, then the previous |
| 142 | bindings, in reverse order of introduction in the table. *) |
| 143 | |
| 144 | val mem : ('a, 'b) t -> 'a -> bool |
| 145 | (** [Hashtbl.mem tbl x] checks if [x] is bound in [tbl]. *) |
| 146 | |
| 147 | val remove : ('a, 'b) t -> 'a -> unit |
| 148 | (** [Hashtbl.remove tbl x] removes the current binding of [x] in [tbl], |
| 149 | restoring the previous binding if it exists. |
| 150 | It does nothing if [x] is not bound in [tbl]. *) |
| 151 | |
| 152 | val replace : ('a, 'b) t -> key:'a -> data:'b -> unit |
| 153 | (** [Hashtbl.replace tbl ~key ~data] replaces the current binding of [key] |
| 154 | in [tbl] by a binding of [key] to [data]. If [key] is unbound in [tbl], |
| 155 | a binding of [key] to [data] is added to [tbl]. |
| 156 | This is functionally equivalent to {!remove}[ tbl key] |
| 157 | followed by {!add}[ tbl key data]. *) |
| 158 | |
| 159 | val iter : f:(key:'a -> data:'b -> unit) -> ('a, 'b) t -> unit |
| 160 | (** [Hashtbl.iter ~f tbl] applies [f] to all bindings in table [tbl]. |
| 161 | [f] receives the key as first argument, and the associated value |
| 162 | as second argument. Each binding is presented exactly once to [f]. |
| 163 | |
| 164 | The order in which the bindings are passed to [f] is unspecified. |
| 165 | However, if the table contains several bindings for the same key, |
| 166 | they are passed to [f] in reverse order of introduction, that is, |
| 167 | the most recent binding is passed first. |
| 168 | |
| 169 | If the hash table was created in non-randomized mode, the order |
| 170 | in which the bindings are enumerated is reproducible between |
| 171 | successive runs of the program, and even between minor versions |
| 172 | of OCaml. For randomized hash tables, the order of enumeration |
| 173 | is entirely random. |
| 174 | |
| 175 | The behavior is not specified if the hash table is modified |
| 176 | by [f] during the iteration. |
| 177 | *) |
| 178 | |
| 179 | val filter_map_inplace: f:(key:'a -> data:'b -> 'b option) -> ('a, 'b) t -> |
| 180 | unit |
| 181 | (** [Hashtbl.filter_map_inplace ~f tbl] applies [f] to all bindings in |
| 182 | table [tbl] and update each binding depending on the result of |
| 183 | [f]. If [f] returns [None], the binding is discarded. If it |
| 184 | returns [Some new_val], the binding is update to associate the key |
| 185 | to [new_val]. |
| 186 | |
| 187 | Other comments for {!iter} apply as well. |
| 188 | @since 4.03 *) |
| 189 | |
| 190 | val fold : |
| 191 | f:(key:'a -> data:'b -> 'acc -> 'acc) -> ('a, 'b) t -> init:'acc -> 'acc |
| 192 | (** [Hashtbl.fold ~f tbl ~init] computes |
| 193 | [(f kN dN ... (f k1 d1 init)...)], |
| 194 | where [k1 ... kN] are the keys of all bindings in [tbl], |
| 195 | and [d1 ... dN] are the associated values. |
| 196 | Each binding is presented exactly once to [f]. |
| 197 | |
| 198 | The order in which the bindings are passed to [f] is unspecified. |
| 199 | However, if the table contains several bindings for the same key, |
| 200 | they are passed to [f] in reverse order of introduction, that is, |
| 201 | the most recent binding is passed first. |
| 202 | |
| 203 | If the hash table was created in non-randomized mode, the order |
| 204 | in which the bindings are enumerated is reproducible between |
| 205 | successive runs of the program, and even between minor versions |
| 206 | of OCaml. For randomized hash tables, the order of enumeration |
| 207 | is entirely random. |
| 208 | |
| 209 | The behavior is not specified if the hash table is modified |
| 210 | by [f] during the iteration. |
| 211 | *) |
| 212 | |
| 213 | val length : ('a, 'b) t -> int |
| 214 | (** [Hashtbl.length tbl] returns the number of bindings in [tbl]. |
| 215 | It takes constant time. Multiple bindings are counted once each, so |
| 216 | [Hashtbl.length] gives the number of times [Hashtbl.iter] calls its |
| 217 | first argument. *) |
| 218 | |
| 219 | val randomize : unit -> unit |
| 220 | (** After a call to [Hashtbl.randomize()], hash tables are created in |
| 221 | randomized mode by default: {!create} returns randomized |
| 222 | hash tables, unless the [~random:false] optional parameter is given. |
| 223 | The same effect can be achieved by setting the [R] parameter in |
| 224 | the [OCAMLRUNPARAM] environment variable. |
| 225 | |
| 226 | It is recommended that applications or Web frameworks that need to |
| 227 | protect themselves against the denial-of-service attack described |
| 228 | in {!create} call [Hashtbl.randomize()] at initialization |
| 229 | time before any domains are created. |
| 230 | |
| 231 | Note that once [Hashtbl.randomize()] was called, there is no way |
| 232 | to revert to the non-randomized default behavior of {!create}. |
| 233 | This is intentional. Non-randomized hash tables can still be |
| 234 | created using [Hashtbl.create ~random:false]. |
| 235 | |
| 236 | @since 4.00 *) |
| 237 | |
| 238 | val is_randomized : unit -> bool |
| 239 | (** Return [true] if the tables are currently created in randomized mode |
| 240 | by default, [false] otherwise. |
| 241 | @since 4.03 *) |
| 242 | |
| 243 | val rebuild : ?random (* thwart tools/sync_stdlib_docs *) :bool -> |
| 244 | ('a, 'b) t -> ('a, 'b) t |
| 245 | (** Return a copy of the given hashtable. Unlike {!copy}, |
| 246 | {!rebuild}[ h] re-hashes all the (key, value) entries of |
| 247 | the original table [h]. The returned hash table is randomized if |
| 248 | [h] was randomized, or the optional [random] parameter is true, or |
| 249 | if the default is to create randomized hash tables; see |
| 250 | {!create} for more information. |
| 251 | |
| 252 | {!rebuild} can safely be used to import a hash table built |
| 253 | by an old version of the {!Hashtbl} module, then marshaled to |
| 254 | persistent storage. After unmarshaling, apply {!rebuild} |
| 255 | to produce a hash table for the current version of the {!Hashtbl} |
| 256 | module. |
| 257 | |
| 258 | @since 4.12 *) |
| 259 | |
| 260 | (** @since 4.00 *) |
| 261 | type statistics = { |
| 262 | num_bindings: int; |
| 263 | (** Number of bindings present in the table. |
| 264 | Same value as returned by {!length}. *) |
| 265 | num_buckets: int; |
| 266 | (** Number of buckets in the table. *) |
| 267 | max_bucket_length: int; |
| 268 | (** Maximal number of bindings per bucket. *) |
| 269 | bucket_histogram: int array |
| 270 | (** Histogram of bucket sizes. This array [histo] has |
| 271 | length [max_bucket_length + 1]. The value of |
| 272 | [histo.(i)] is the number of buckets whose size is [i]. *) |
| 273 | } |
| 274 | |
| 275 | val stats : ('a, 'b) t -> statistics |
| 276 | (** [Hashtbl.stats tbl] returns statistics about the table [tbl]: |
| 277 | number of buckets, size of the biggest bucket, distribution of |
| 278 | buckets by size. |
| 279 | @since 4.00 *) |
| 280 | |
| 281 | (** {1 Hash tables and Sequences} *) |
| 282 | |
| 283 | val to_seq : ('a,'b) t -> ('a * 'b) Seq.t |
| 284 | (** Iterate on the whole table. The order in which the bindings |
| 285 | appear in the sequence is unspecified. However, if the table contains |
| 286 | several bindings for the same key, they appear in reversed order of |
| 287 | introduction, that is, the most recent binding appears first. |
| 288 | |
| 289 | The behavior is not specified if the hash table is modified |
| 290 | during the iteration. |
| 291 | |
| 292 | @since 4.07 *) |
| 293 | |
| 294 | val to_seq_keys : ('a,_) t -> 'a Seq.t |
| 295 | (** Same as [Seq.map fst (to_seq m)] |
| 296 | @since 4.07 *) |
| 297 | |
| 298 | val to_seq_values : (_,'b) t -> 'b Seq.t |
| 299 | (** Same as [Seq.map snd (to_seq m)] |
| 300 | @since 4.07 *) |
| 301 | |
| 302 | val add_seq : ('a,'b) t -> ('a * 'b) Seq.t -> unit |
| 303 | (** Add the given bindings to the table, using {!add} |
| 304 | @since 4.07 *) |
| 305 | |
| 306 | val replace_seq : ('a,'b) t -> ('a * 'b) Seq.t -> unit |
| 307 | (** Add the given bindings to the table, using {!replace} |
| 308 | @since 4.07 *) |
| 309 | |
| 310 | val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t |
| 311 | (** Build a table from the given bindings. The bindings are added |
| 312 | in the same order they appear in the sequence, using {!replace_seq}, |
| 313 | which means that if two pairs have the same key, only the latest one |
| 314 | will appear in the table. |
| 315 | @since 4.07 *) |
| 316 | |
| 317 | (** {1 Functorial interface} *) |
| 318 | |
| 319 | (** The functorial interface allows the use of specific comparison |
| 320 | and hash functions, either for performance/security concerns, |
| 321 | or because keys are not hashable/comparable with the polymorphic builtins. |
| 322 | |
| 323 | For instance, one might want to specialize a table for integer keys: |
| 324 | {[ |
| 325 | module IntHash = |
| 326 | struct |
| 327 | type t = int |
| 328 | let equal i j = i=j |
| 329 | let hash i = i land max_int |
| 330 | end |
| 331 | |
| 332 | module IntHashtbl = Hashtbl.Make(IntHash) |
| 333 | |
| 334 | let h = IntHashtbl.create 17 in |
| 335 | IntHashtbl.add h 12 "hello" |
| 336 | ]} |
| 337 | |
| 338 | This creates a new module [IntHashtbl], with a new type ['a |
| 339 | IntHashtbl.t] of tables from [int] to ['a]. In this example, [h] |
| 340 | contains [string] values so its type is [string IntHashtbl.t]. |
| 341 | |
| 342 | Note that the new type ['a IntHashtbl.t] is not compatible with |
| 343 | the type [('a,'b) Hashtbl.t] of the generic interface. For |
| 344 | example, [Hashtbl.length h] would not type-check, you must use |
| 345 | [IntHashtbl.length]. |
| 346 | *) |
| 347 | |
| 348 | module type HashedType = |
| 349 | sig |
| 350 | type t |
| 351 | (** The type of the hashtable keys. *) |
| 352 | |
| 353 | val equal : t -> t -> bool |
| 354 | (** The equality predicate used to compare keys. *) |
| 355 | |
| 356 | val hash : t -> int |
| 357 | (** A hashing function on keys. It must be such that if two keys are |
| 358 | equal according to [equal], then they have identical hash values |
| 359 | as computed by [hash]. |
| 360 | Examples: suitable ([equal], [hash]) pairs for arbitrary key |
| 361 | types include |
| 362 | - ([(=)], {!hash}) for comparing objects by structure |
| 363 | (provided objects do not contain floats) |
| 364 | - ([(fun x y -> compare x y = 0)], {!hash}) |
| 365 | for comparing objects by structure |
| 366 | and handling {!Stdlib.nan} correctly |
| 367 | - ([(==)], {!hash}) for comparing objects by physical |
| 368 | equality (e.g. for mutable or cyclic objects). *) |
| 369 | end |
| 370 | (** The input signature of the functor {!Make}. *) |
| 371 | |
| 372 | module type S = |
| 373 | sig |
| 374 | type key |
| 375 | type !'a t |
| 376 | val create : int -> 'a t |
| 377 | val clear : 'a t -> unit |
| 378 | val reset : 'a t -> unit (** @since 4.00 *) |
| 379 | |
| 380 | val copy : 'a t -> 'a t |
| 381 | val add : 'a t -> key:key -> data:'a -> unit |
| 382 | val remove : 'a t -> key -> unit |
| 383 | val find : 'a t -> key -> 'a |
| 384 | val find_opt : 'a t -> key -> 'a option |
| 385 | (** @since 4.05 *) |
| 386 | |
| 387 | val find_all : 'a t -> key -> 'a list |
| 388 | val replace : 'a t -> key:key -> data:'a -> unit |
| 389 | val mem : 'a t -> key -> bool |
| 390 | val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit |
| 391 | val filter_map_inplace: f:(key:key -> data:'a -> 'a option) -> 'a t -> |
| 392 | unit |
| 393 | (** @since 4.03 *) |
| 394 | |
| 395 | val fold : |
| 396 | f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc |
| 397 | val length : 'a t -> int |
| 398 | val stats: 'a t -> statistics (** @since 4.00 *) |
| 399 | |
| 400 | val to_seq : 'a t -> (key * 'a) Seq.t |
| 401 | (** @since 4.07 *) |
| 402 | |
| 403 | val to_seq_keys : _ t -> key Seq.t |
| 404 | (** @since 4.07 *) |
| 405 | |
| 406 | val to_seq_values : 'a t -> 'a Seq.t |
| 407 | (** @since 4.07 *) |
| 408 | |
| 409 | val add_seq : 'a t -> (key * 'a) Seq.t -> unit |
| 410 | (** @since 4.07 *) |
| 411 | |
| 412 | val replace_seq : 'a t -> (key * 'a) Seq.t -> unit |
| 413 | (** @since 4.07 *) |
| 414 | |
| 415 | val of_seq : (key * 'a) Seq.t -> 'a t |
| 416 | (** @since 4.07 *) |
| 417 | end |
| 418 | (** The output signature of the functor {!Make}. *) |
| 419 | |
| 420 | module Make (H : HashedType) : S with type key = H.t |
| 421 | (** Functor building an implementation of the hashtable structure. |
| 422 | The functor [Hashtbl.Make] returns a structure containing |
| 423 | a type [key] of keys and a type ['a t] of hash tables |
| 424 | associating data of type ['a] to keys of type [key]. |
| 425 | The operations perform similarly to those of the generic |
| 426 | interface, but use the hashing and equality functions |
| 427 | specified in the functor argument [H] instead of generic |
| 428 | equality and hashing. Since the hash function is not seeded, |
| 429 | the [create] operation of the result structure always returns |
| 430 | non-randomized hash tables. *) |
| 431 | |
| 432 | module type SeededHashedType = |
| 433 | sig |
| 434 | type t |
| 435 | (** The type of the hashtable keys. *) |
| 436 | |
| 437 | val equal: t -> t -> bool |
| 438 | (** The equality predicate used to compare keys. *) |
| 439 | |
| 440 | val seeded_hash: int -> t -> int |
| 441 | (** A seeded hashing function on keys. The first argument is |
| 442 | the seed. It must be the case that if [equal x y] is true, |
| 443 | then [seeded_hash seed x = seeded_hash seed y] for any value of |
| 444 | [seed]. A suitable choice for [seeded_hash] is the function |
| 445 | {!Hashtbl.seeded_hash} below. *) |
| 446 | end |
| 447 | (** The input signature of the functor {!MakeSeeded}. |
| 448 | @since 4.00 *) |
| 449 | |
| 450 | module type SeededS = |
| 451 | sig |
| 452 | type key |
| 453 | type !'a t |
| 454 | val create : ?random (* thwart tools/sync_stdlib_docs *) :bool -> |
| 455 | int -> 'a t |
| 456 | val clear : 'a t -> unit |
| 457 | val reset : 'a t -> unit |
| 458 | val copy : 'a t -> 'a t |
| 459 | val add : 'a t -> key:key -> data:'a -> unit |
| 460 | val remove : 'a t -> key -> unit |
| 461 | val find : 'a t -> key -> 'a |
| 462 | val find_opt : 'a t -> key -> 'a option (** @since 4.05 *) |
| 463 | |
| 464 | val find_all : 'a t -> key -> 'a list |
| 465 | val replace : 'a t -> key:key -> data:'a -> unit |
| 466 | val mem : 'a t -> key -> bool |
| 467 | val iter : f:(key:key -> data:'a -> unit) -> 'a t -> unit |
| 468 | val filter_map_inplace: f:(key:key -> data:'a -> 'a option) -> 'a t -> |
| 469 | unit |
| 470 | (** @since 4.03 *) |
| 471 | |
| 472 | val fold : |
| 473 | f:(key:key -> data:'a -> 'acc -> 'acc) -> 'a t -> init:'acc -> 'acc |
| 474 | val length : 'a t -> int |
| 475 | val stats: 'a t -> statistics |
| 476 | |
| 477 | val to_seq : 'a t -> (key * 'a) Seq.t |
| 478 | (** @since 4.07 *) |
| 479 | |
| 480 | val to_seq_keys : _ t -> key Seq.t |
| 481 | (** @since 4.07 *) |
| 482 | |
| 483 | val to_seq_values : 'a t -> 'a Seq.t |
| 484 | (** @since 4.07 *) |
| 485 | |
| 486 | val add_seq : 'a t -> (key * 'a) Seq.t -> unit |
| 487 | (** @since 4.07 *) |
| 488 | |
| 489 | val replace_seq : 'a t -> (key * 'a) Seq.t -> unit |
| 490 | (** @since 4.07 *) |
| 491 | |
| 492 | val of_seq : (key * 'a) Seq.t -> 'a t |
| 493 | (** @since 4.07 *) |
| 494 | end |
| 495 | (** The output signature of the functor {!MakeSeeded}. |
| 496 | @since 4.00 *) |
| 497 | |
| 498 | module MakeSeeded (H : SeededHashedType) : SeededS with type key = H.t |
| 499 | (** Functor building an implementation of the hashtable structure. |
| 500 | The functor [Hashtbl.MakeSeeded] returns a structure containing |
| 501 | a type [key] of keys and a type ['a t] of hash tables |
| 502 | associating data of type ['a] to keys of type [key]. |
| 503 | The operations perform similarly to those of the generic |
| 504 | interface, but use the seeded hashing and equality functions |
| 505 | specified in the functor argument [H] instead of generic |
| 506 | equality and hashing. The [create] operation of the |
| 507 | result structure supports the [~random] optional parameter |
| 508 | and returns randomized hash tables if [~random:true] is passed |
| 509 | or if randomization is globally on (see {!Hashtbl.randomize}). |
| 510 | @since 4.00 *) |
| 511 | |
| 512 | |
| 513 | (** {1 The polymorphic hash functions} *) |
| 514 | |
| 515 | |
| 516 | val hash : 'a -> int |
| 517 | (** [Hashtbl.hash x] associates a nonnegative integer to any value of |
| 518 | any type. It is guaranteed that |
| 519 | if [x = y] or [Stdlib.compare x y = 0], then [hash x = hash y]. |
| 520 | Moreover, [hash] always terminates, even on cyclic structures. *) |
| 521 | |
| 522 | val seeded_hash : int -> 'a -> int |
| 523 | (** A variant of {!hash} that is further parameterized by |
| 524 | an integer seed. |
| 525 | @since 4.00 *) |
| 526 | |
| 527 | val hash_param : int -> int -> 'a -> int |
| 528 | (** [Hashtbl.hash_param meaningful total x] computes a hash value for [x], |
| 529 | with the same properties as for [hash]. The two extra integer |
| 530 | parameters [meaningful] and [total] give more precise control over |
| 531 | hashing. Hashing performs a breadth-first, left-to-right traversal |
| 532 | of the structure [x], stopping after [meaningful] meaningful nodes |
| 533 | were encountered, or [total] nodes (meaningful or not) were |
| 534 | encountered. If [total] as specified by the user exceeds a certain |
| 535 | value, currently 256, then it is capped to that value. |
| 536 | Meaningful nodes are: integers; floating-point |
| 537 | numbers; strings; characters; booleans; and constant |
| 538 | constructors. Larger values of [meaningful] and [total] means that |
| 539 | more nodes are taken into account to compute the final hash value, |
| 540 | and therefore collisions are less likely to happen. However, |
| 541 | hashing takes longer. The parameters [meaningful] and [total] |
| 542 | govern the tradeoff between accuracy and speed. As default |
| 543 | choices, {!hash} and {!seeded_hash} take |
| 544 | [meaningful = 10] and [total = 100]. *) |
| 545 | |
| 546 | val seeded_hash_param : int -> int -> int -> 'a -> int |
| 547 | (** A variant of {!hash_param} that is further parameterized by |
| 548 | an integer seed. Usage: |
| 549 | [Hashtbl.seeded_hash_param meaningful total seed x]. |
| 550 | @since 4.00 *) |
| 551 | |
| 552 | (** {1:examples Examples} |
| 553 | |
| 554 | {2 Basic Example} |
| 555 | |
| 556 | {[ |
| 557 | (* 0...99 *) |
| 558 | let seq = Seq.ints 0 |> Seq.take 100 |
| 559 | |
| 560 | (* build from Seq.t *) |
| 561 | # let tbl = |
| 562 | seq |
| 563 | |> Seq.map (fun x -> x, string_of_int x) |
| 564 | |> Hashtbl.of_seq |
| 565 | val tbl : (int, string) Hashtbl.t = <abstr> |
| 566 | |
| 567 | # Hashtbl.length tbl |
| 568 | - : int = 100 |
| 569 | |
| 570 | # Hashtbl.find_opt tbl 32 |
| 571 | - : string option = Some "32" |
| 572 | |
| 573 | # Hashtbl.find_opt tbl 166 |
| 574 | - : string option = None |
| 575 | |
| 576 | # Hashtbl.replace tbl 166 "one six six" |
| 577 | - : unit = () |
| 578 | |
| 579 | # Hashtbl.find_opt tbl 166 |
| 580 | - : string option = Some "one six six" |
| 581 | |
| 582 | # Hashtbl.length tbl |
| 583 | - : int = 101 |
| 584 | ]} |
| 585 | |
| 586 | |
| 587 | {2 Counting Elements} |
| 588 | |
| 589 | Given a sequence of elements (here, a {!Seq.t}), we want to count how many |
| 590 | times each distinct element occurs in the sequence. A simple way to do this, |
| 591 | assuming the elements are comparable and hashable, is to use a hash table |
| 592 | that maps elements to their number of occurrences. |
| 593 | |
| 594 | Here we illustrate that principle using a sequence of (ascii) characters |
| 595 | (type [char]). |
| 596 | We use a custom [Char_tbl] specialized for [char]. |
| 597 | |
| 598 | {[ |
| 599 | # module Char_tbl = Hashtbl.Make(struct |
| 600 | type t = char |
| 601 | let equal = Char.equal |
| 602 | let hash = Hashtbl.hash |
| 603 | end) |
| 604 | |
| 605 | (* count distinct occurrences of chars in [seq] *) |
| 606 | # let count_chars (seq : char Seq.t) : _ list = |
| 607 | let counts = Char_tbl.create 16 in |
| 608 | Seq.iter |
| 609 | (fun c -> |
| 610 | let count_c = |
| 611 | Char_tbl.find_opt counts c |
| 612 | |> Option.value ~default:0 |
| 613 | in |
| 614 | Char_tbl.replace counts c (count_c + 1)) |
| 615 | seq; |
| 616 | (* turn into a list *) |
| 617 | Char_tbl.fold (fun c n l -> (c,n) :: l) counts [] |
| 618 | |> List.sort (fun (c1,_)(c2,_) -> Char.compare c1 c2) |
| 619 | val count_chars : Char_tbl.key Seq.t -> (Char.t * int) list = <fun> |
| 620 | |
| 621 | (* basic seq from a string *) |
| 622 | # let seq = String.to_seq "hello world, and all the camels in it!" |
| 623 | val seq : char Seq.t = <fun> |
| 624 | |
| 625 | # count_chars seq |
| 626 | - : (Char.t * int) list = |
| 627 | [(' ', 7); ('!', 1); (',', 1); ('a', 3); ('c', 1); ('d', 2); ('e', 3); |
| 628 | ('h', 2); ('i', 2); ('l', 6); ('m', 1); ('n', 2); ('o', 2); ('r', 1); |
| 629 | ('s', 1); ('t', 2); ('w', 1)] |
| 630 | |
| 631 | (* "abcabcabc..." *) |
| 632 | # let seq2 = |
| 633 | Seq.cycle (String.to_seq "abc") |> Seq.take 31 |
| 634 | val seq2 : char Seq.t = <fun> |
| 635 | |
| 636 | # String.of_seq seq2 |
| 637 | - : String.t = "abcabcabcabcabcabcabcabcabcabca" |
| 638 | |
| 639 | # count_chars seq2 |
| 640 | - : (Char.t * int) list = [('a', 11); ('b', 10); ('c', 10)] |
| 641 | |
| 642 | ]} |
| 643 | |
| 644 | *) |