1Hashtbl(3) OCaml library Hashtbl(3)
2
3
4
6 Hashtbl - Hash tables and hash functions.
7
9 Module Hashtbl
10
12 Module Hashtbl
13 : sig end
14
15
16 Hash tables and hash functions.
17
18 Hash tables are hashed association tables, with in-place modification.
19
20
21
22
23
24
25
26 Generic interface
27 type ('a, 'b) t
28
29
30 The type of hash tables from type 'a to type 'b .
31
32
33
34 val create : ?random:bool -> int -> ('a, 'b) t
35
36
37 Hashtbl.create n creates a new, empty hash table, with initial size n .
38 For best results, n should be on the order of the expected number of
39 elements that will be in the table. The table grows as needed, so n is
40 just an initial guess.
41
42 The optional random parameter (a boolean) controls whether the internal
43 organization of the hash table is randomized at each execution of
44 Hashtbl.create or deterministic over all executions.
45
46 A hash table that is created with ~random:false uses a fixed hash func‐
47 tion ( Hashtbl.hash ) to distribute keys among buckets. As a conse‐
48 quence, collisions between keys happen deterministically. In Web-fac‐
49 ing applications or other security-sensitive applications, the deter‐
50 ministic collision patterns can be exploited by a malicious user to
51 create a denial-of-service attack: the attacker sends input crafted to
52 create many collisions in the table, slowing the application down.
53
54 A hash table that is created with ~random:true uses the seeded hash
55 function Hashtbl.seeded_hash with a seed that is randomly chosen at
56 hash table creation time. In effect, the hash function used is ran‐
57 domly selected among 2^{30} different hash functions. All these hash
58 functions have different collision patterns, rendering ineffective the
59 denial-of-service attack described above. However, because of random‐
60 ization, enumerating all elements of the hash table using Hashtbl.fold
61 or Hashtbl.iter is no longer deterministic: elements are enumerated in
62 different orders at different runs of the program.
63
64 If no ~random parameter is given, hash tables are created in non-random
65 mode by default. This default can be changed either programmatically
66 by calling Hashtbl.randomize or by setting the R flag in the OCAMLRUN‐
67 PARAM environment variable.
68
69
70 Before4.00.0 the random parameter was not present and all hash tables
71 were created in non-randomized mode.
72
73
74
75
76 val clear : ('a, 'b) t -> unit
77
78 Empty a hash table. Use reset instead of clear to shrink the size of
79 the bucket table to its initial size.
80
81
82
83 val reset : ('a, 'b) t -> unit
84
85 Empty a hash table and shrink the size of the bucket table to its ini‐
86 tial size.
87
88
89 Since 4.00.0
90
91
92
93 val copy : ('a, 'b) t -> ('a, 'b) t
94
95 Return a copy of the given hashtable.
96
97
98
99 val add : ('a, 'b) t -> 'a -> 'b -> unit
100
101
102 Hashtbl.add tbl x y adds a binding of x to y in table tbl . Previous
103 bindings for x are not removed, but simply hidden. That is, after per‐
104 forming Hashtbl.remove tbl x , the previous binding for x , if any, is
105 restored. (Same behavior as with association lists.)
106
107
108
109 val find : ('a, 'b) t -> 'a -> 'b
110
111
112 Hashtbl.find tbl x returns the current binding of x in tbl , or raises
113 Not_found if no such binding exists.
114
115
116
117 val find_opt : ('a, 'b) t -> 'a -> 'b option
118
119
120 Hashtbl.find_opt tbl x returns the current binding of x in tbl , or
121 None if no such binding exists.
122
123
124 Since 4.05
125
126
127
128 val find_all : ('a, 'b) t -> 'a -> 'b list
129
130
131 Hashtbl.find_all tbl x returns the list of all data associated with x
132 in tbl . The current binding is returned first, then the previous
133 bindings, in reverse order of introduction in the table.
134
135
136
137 val mem : ('a, 'b) t -> 'a -> bool
138
139
140 Hashtbl.mem tbl x checks if x is bound in tbl .
141
142
143
144 val remove : ('a, 'b) t -> 'a -> unit
145
146
147 Hashtbl.remove tbl x removes the current binding of x in tbl , restor‐
148 ing the previous binding if it exists. It does nothing if x is not
149 bound in tbl .
150
151
152
153 val replace : ('a, 'b) t -> 'a -> 'b -> unit
154
155
156 Hashtbl.replace tbl x y replaces the current binding of x in tbl by a
157 binding of x to y . If x is unbound in tbl , a binding of x to y is
158 added to tbl . This is functionally equivalent to Hashtbl.remove tbl x
159 followed by Hashtbl.add tbl x y .
160
161
162
163 val iter : ('a -> 'b -> unit) -> ('a, 'b) t -> unit
164
165
166 Hashtbl.iter f tbl applies f to all bindings in table tbl . f receives
167 the key as first argument, and the associated value as second argument.
168 Each binding is presented exactly once to f .
169
170 The order in which the bindings are passed to f is unspecified. How‐
171 ever, if the table contains several bindings for the same key, they are
172 passed to f in reverse order of introduction, that is, the most recent
173 binding is passed first.
174
175 If the hash table was created in non-randomized mode, the order in
176 which the bindings are enumerated is reproducible between successive
177 runs of the program, and even between minor versions of OCaml. For
178 randomized hash tables, the order of enumeration is entirely random.
179
180 The behavior is not defined if the hash table is modified by f during
181 the iteration.
182
183
184
185 val filter_map_inplace : ('a -> 'b -> 'b option) -> ('a, 'b) t -> unit
186
187
188 Hashtbl.filter_map_inplace f tbl applies f to all bindings in table tbl
189 and update each binding depending on the result of f . If f returns
190 None , the binding is discarded. If it returns Some new_val , the
191 binding is update to associate the key to new_val .
192
193 Other comments for Hashtbl.iter apply as well.
194
195
196 Since 4.03.0
197
198
199
200 val fold : ('a -> 'b -> 'c -> 'c) -> ('a, 'b) t -> 'c -> 'c
201
202
203 Hashtbl.fold f tbl init computes (f kN dN ... (f k1 d1 init)...) ,
204 where k1 ... kN are the keys of all bindings in tbl , and d1 ... dN are
205 the associated values. Each binding is presented exactly once to f .
206
207 The order in which the bindings are passed to f is unspecified. How‐
208 ever, if the table contains several bindings for the same key, they are
209 passed to f in reverse order of introduction, that is, the most recent
210 binding is passed first.
211
212 If the hash table was created in non-randomized mode, the order in
213 which the bindings are enumerated is reproducible between successive
214 runs of the program, and even between minor versions of OCaml. For
215 randomized hash tables, the order of enumeration is entirely random.
216
217 The behavior is not defined if the hash table is modified by f during
218 the iteration.
219
220
221
222 val length : ('a, 'b) t -> int
223
224
225 Hashtbl.length tbl returns the number of bindings in tbl . It takes
226 constant time. Multiple bindings are counted once each, so
227 Hashtbl.length gives the number of times Hashtbl.iter calls its first
228 argument.
229
230
231
232 val randomize : unit -> unit
233
234 After a call to Hashtbl.randomize() , hash tables are created in ran‐
235 domized mode by default: Hashtbl.create returns randomized hash tables,
236 unless the ~random:false optional parameter is given. The same effect
237 can be achieved by setting the R parameter in the OCAMLRUNPARAM envi‐
238 ronment variable.
239
240 It is recommended that applications or Web frameworks that need to pro‐
241 tect themselves against the denial-of-service attack described in
242 Hashtbl.create call Hashtbl.randomize() at initialization time.
243
244 Note that once Hashtbl.randomize() was called, there is no way to
245 revert to the non-randomized default behavior of Hashtbl.create . This
246 is intentional. Non-randomized hash tables can still be created using
247 Hashtbl.create ~random:false .
248
249
250 Since 4.00.0
251
252
253
254 val is_randomized : unit -> bool
255
256 return if the tables are currently created in randomized mode by
257 default
258
259
260 Since 4.03.0
261
262
263 type statistics = {
264 num_bindings : int ; (* Number of bindings present in the table.
265 Same value as returned by Hashtbl.length .
266 *)
267 num_buckets : int ; (* Number of buckets in the table.
268 *)
269 max_bucket_length : int ; (* Maximal number of bindings per bucket.
270 *)
271 bucket_histogram : int array ; (* Histogram of bucket sizes. This
272 array histo has length max_bucket_length + 1 . The value of histo.(i)
273 is the number of buckets whose size is i .
274 *)
275 }
276
277
278 Since 4.00.0
279
280
281
282 val stats : ('a, 'b) t -> statistics
283
284
285 Hashtbl.stats tbl returns statistics about the table tbl : number of
286 buckets, size of the biggest bucket, distribution of buckets by size.
287
288
289 Since 4.00.0
290
291
292
293
294 Iterators
295 val to_seq : ('a, 'b) t -> ('a * 'b) Seq.t
296
297 Iterate on the whole table. The order in which the bindings appear in
298 the sequence is unspecified. However, if the table contains several
299 bindings for the same key, they appear in reversed order of introduc‐
300 tion, that is, the most recent binding appears first.
301
302 The behavior is not defined if the hash table is modified during the
303 iteration.
304
305
306 Since 4.07
307
308
309
310 val to_seq_keys : ('a, 'b) t -> 'a Seq.t
311
312 Same as Seq.map fst (to_seq m)
313
314
315
316 Since 4.07
317
318
319
320 val to_seq_values : ('a, 'b) t -> 'b Seq.t
321
322 Same as Seq.map snd (to_seq m)
323
324
325
326 Since 4.07
327
328
329
330 val add_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
331
332 Add the given bindings to the table, using Hashtbl.add
333
334
335
336 Since 4.07
337
338
339
340 val replace_seq : ('a, 'b) t -> ('a * 'b) Seq.t -> unit
341
342 Add the given bindings to the table, using Hashtbl.replace
343
344
345
346 Since 4.07
347
348
349
350 val of_seq : ('a * 'b) Seq.t -> ('a, 'b) t
351
352 Build a table from the given bindings. The bindings are added in the
353 same order they appear in the sequence, using Hashtbl.replace_seq ,
354 which means that if two pairs have the same key, only the latest one
355 will appear in the table.
356
357
358 Since 4.07
359
360
361
362
363 Functorial interface
364 The functorial interface allows the use of specific comparison and hash
365 functions, either for performance/security concerns, or because keys
366 are not hashable/comparable with the polymorphic builtins.
367
368 For instance, one might want to specialize a table for integer keys:
369 module IntHash =
370 struct
371 type t = int
372 let equal i j = i=j
373 let hash i = i land max_int
374 end
375
376 module IntHashtbl = Hashtbl.Make(IntHash)
377
378 let h = IntHashtbl.create 17 in
379 IntHashtbl.add h 12 "hello"
380
381
382 This creates a new module IntHashtbl , with a new type 'a
383 IntHashtbl.t of tables from int to 'a . In this example, h contains
384 string values so its type is string IntHashtbl.t .
385
386 Note that the new type 'a IntHashtbl.t is not compatible with the type
387 ('a,'b) Hashtbl.t of the generic interface. For example, Hashtbl.length
388 h would not type-check, you must use IntHashtbl.length .
389
390 module type HashedType = sig end
391
392
393 The input signature of the functor Hashtbl.Make .
394
395
396 module type S = sig end
397
398
399 The output signature of the functor Hashtbl.Make .
400
401
402 module Make : functor (H : HashedType) -> sig end
403
404
405 Functor building an implementation of the hashtable structure. The
406 functor Hashtbl.Make returns a structure containing a type key of keys
407 and a type 'a t of hash tables associating data of type 'a to keys of
408 type key . The operations perform similarly to those of the generic
409 interface, but use the hashing and equality functions specified in the
410 functor argument H instead of generic equality and hashing. Since the
411 hash function is not seeded, the create operation of the result struc‐
412 ture always returns non-randomized hash tables.
413
414
415 module type SeededHashedType = sig end
416
417
418 The input signature of the functor Hashtbl.MakeSeeded .
419
420
421 Since 4.00.0
422
423
424 module type SeededS = sig end
425
426
427 The output signature of the functor Hashtbl.MakeSeeded .
428
429
430 Since 4.00.0
431
432
433 module MakeSeeded : functor (H : SeededHashedType) -> sig end
434
435
436 Functor building an implementation of the hashtable structure. The
437 functor Hashtbl.MakeSeeded returns a structure containing a type key of
438 keys and a type 'a t of hash tables associating data of type 'a to keys
439 of type key . The operations perform similarly to those of the generic
440 interface, but use the seeded hashing and equality functions specified
441 in the functor argument H instead of generic equality and hashing. The
442 create operation of the result structure supports the ~random optional
443 parameter and returns randomized hash tables if ~random:true is passed
444 or if randomization is globally on (see Hashtbl.randomize ).
445
446
447 Since 4.00.0
448
449
450
451
452 The polymorphic hash functions
453 val hash : 'a -> int
454
455
456 Hashtbl.hash x associates a nonnegative integer to any value of any
457 type. It is guaranteed that if x = y or Stdlib.compare x y = 0 , then
458 hash x = hash y . Moreover, hash always terminates, even on cyclic
459 structures.
460
461
462
463 val seeded_hash : int -> 'a -> int
464
465 A variant of Hashtbl.hash that is further parameterized by an integer
466 seed.
467
468
469 Since 4.00.0
470
471
472
473 val hash_param : int -> int -> 'a -> int
474
475
476 Hashtbl.hash_param meaningful total x computes a hash value for x ,
477 with the same properties as for hash . The two extra integer parameters
478 meaningful and total give more precise control over hashing. Hashing
479 performs a breadth-first, left-to-right traversal of the structure x ,
480 stopping after meaningful meaningful nodes were encountered, or total
481 nodes (meaningful or not) were encountered. If total as specified by
482 the user exceeds a certain value, currently 256, then it is capped to
483 that value. Meaningful nodes are: integers; floating-point numbers;
484 strings; characters; booleans; and constant constructors. Larger values
485 of meaningful and total means that more nodes are taken into account to
486 compute the final hash value, and therefore collisions are less likely
487 to happen. However, hashing takes longer. The parameters meaningful
488 and total govern the tradeoff between accuracy and speed. As default
489 choices, Hashtbl.hash and Hashtbl.seeded_hash take meaningful = 10 and
490 total = 100 .
491
492
493
494 val seeded_hash_param : int -> int -> int -> 'a -> int
495
496 A variant of Hashtbl.hash_param that is further parameterized by an
497 integer seed. Usage: Hashtbl.seeded_hash_param meaningful total seed x
498 .
499
500
501 Since 4.00.0
502
503
504
505
506
507OCamldoc 2020-02-27 Hashtbl(3)