patricia.ml 31.9 KB
 POTTIER Francois committed Mar 24, 2017 1 2 3 4 5 6 7 8 9 10 11 12 13 (******************************************************************************) (* *) (* Menhir *) (* *) (* François Pottier, Inria Paris *) (* Yann Régis-Gianas, PPS, Université Paris Diderot *) (* *) (* Copyright Inria. All rights reserved. This file is distributed under the *) (* terms of the GNU General Public License version 2, as described in the *) (* file LICENSE. *) (* *) (******************************************************************************)  fpottier committed Mar 01, 2013 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 (* This is an implementation of Patricia trees, following Chris Okasaki's paper at the 1998 ML Workshop in Baltimore. Both big-endian and little-endian trees are provided. Both sets and maps are implemented on top of Patricia trees. *) (*i --------------------------------------------------------------------------------------------------------------- i*) (*s \mysection{Little-endian vs big-endian trees} *) (* A tree is little-endian if it expects the key's least significant bits to be tested first during a search. It is big-endian if it expects the key's most significant bits to be tested first. Most of the code is independent of this design choice, so it is written as a functor, parameterized by a small structure which defines endianness. Here is the interface which must be adhered to by such a structure. *) module Endianness = struct module type S = sig (* A mask is an integer with a single one bit (i.e. a power of 2). *) type mask = int (* [branching_bit] accepts two distinct integers and returns a mask which identifies the first bit where they differ. The meaning of first'' varies according to the endianness being implemented. *) val branching_bit: int -> int -> mask (* [mask i m] returns an integer [i'], where all bits which [m] says are relevant are identical to those in [i], and all others are set to some unspecified, but fixed value. Which bits are relevant'' according to a given mask varies according to the endianness being implemented. *) val mask: int -> mask -> int (* [shorter m1 m2] returns [true] if and only if [m1] describes a shorter prefix than [m2], i.e. if it makes fewer bits relevant. Which bits are relevant'' according to a given mask varies according to the endianness being implemented. *) val shorter: mask -> mask -> bool end (* Now, let us define [Little] and [Big], two possible [Endiannness] choices. *) module Little = struct type mask = int let lowest_bit x = x land (-x) (* Performing a logical xor'' of [i0] and [i1] yields a bit field where all differences between [i0] and [i1] show up as one bits. (There must be at least one, since [i0] and [i1] are distinct.) The first'' one is the lowest bit in this bit field, since we are checking least significant bits first. *) let branching_bit i0 i1 = lowest_bit (i0 lxor i1) (* The relevant'' bits in an integer [i] are those which are found (strictly) to the right of the single one bit in the mask [m]. We keep these bits, and set all others to 0. *) let mask i m = i land (m-1) (* The smaller [m] is, the fewer bits are relevant. *) let shorter = (<) end module Big = struct type mask = int let lowest_bit x = x land (-x) let rec highest_bit x = let m = lowest_bit x in if x = m then  POTTIER Francois committed Apr 28, 2016 93  m  fpottier committed Mar 01, 2013 94  else  POTTIER Francois committed Apr 28, 2016 95  highest_bit (x - m)  fpottier committed Mar 01, 2013 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154  (* Performing a logical xor'' of [i0] and [i1] yields a bit field where all differences between [i0] and [i1] show up as one bits. (There must be at least one, since [i0] and [i1] are distinct.) The first'' one is the highest bit in this bit field, since we are checking most significant bits first. In Okasaki's paper, this loop is sped up by computing a conservative initial guess. Indeed, the bit at which the two prefixes disagree must be somewhere within the shorter prefix, so we can begin searching at the least-significant valid bit in the shorter prefix. Unfortunately, to allow computing the initial guess, the main code has to pass in additional parameters, e.g. a mask which describes the length of each prefix. This pollutes'' the endianness-independent code. For this reason, this optimization isn't implemented here. *) let branching_bit i0 i1 = highest_bit (i0 lxor i1) (* The relevant'' bits in an integer [i] are those which are found (strictly) to the left of the single one bit in the mask [m]. We keep these bits, and set all others to 0. Okasaki uses a different convention, which allows big-endian Patricia trees to masquerade as binary search trees. This feature does not seem to be useful here. *) let mask i m = i land (lnot (2*m-1)) (* The smaller [m] is, the more bits are relevant. *) let shorter = (>) end end (*i --------------------------------------------------------------------------------------------------------------- i*) (*s \mysection{Patricia-tree-based maps} *) module Make (X : Endianness.S) = struct (* Patricia trees are maps whose keys are integers. *) type key = int (* A tree is either empty, or a leaf node, containing both the integer key and a piece of data, or a binary node. Each binary node carries two integers. The first one is the longest common prefix of all keys in this sub-tree. The second integer is the branching bit. It is an integer with a single one bit (i.e. a power of 2), which describes the bit being tested at this node. *) type 'a t = | Empty | Leaf of int * 'a | Branch of int * X.mask * 'a t * 'a t (* The empty map. *) let empty = Empty (* [choose m] returns an arbitrarily chosen binding in [m], if [m] is nonempty, and raises [Not_found] otherwise. *) let rec choose = function | Empty ->  POTTIER Francois committed Apr 28, 2016 155  raise Not_found  fpottier committed Mar 01, 2013 156  | Leaf (key, data) ->  POTTIER Francois committed Apr 28, 2016 157  key, data  fpottier committed Mar 01, 2013 158  | Branch (_, _, tree0, _) ->  POTTIER Francois committed Apr 28, 2016 159  choose tree0  fpottier committed Mar 01, 2013 160 161 162 163 164 165 166 167 168 169 170  (* [lookup k m] looks up the value associated to the key [k] in the map [m], and raises [Not_found] if no value is bound to [k]. This implementation takes branches \emph{without} checking whether the key matches the prefix found at the current node. This means that a query for a non-existent key shall be detected only when finally reaching a leaf, rather than higher up in the tree. This strategy is better when (most) queries are expected to be successful. *) let rec lookup key = function | Empty ->  POTTIER Francois committed Apr 28, 2016 171  raise Not_found  fpottier committed Mar 01, 2013 172  | Leaf (key', data) ->  POTTIER Francois committed Apr 28, 2016 173 174 175 176  if key = key' then data else raise Not_found  fpottier committed Mar 01, 2013 177  | Branch (_, mask, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 178  lookup key (if (key land mask) = 0 then tree0 else tree1)  fpottier committed Mar 01, 2013 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231  let find = lookup (* [mem k m] tells whether the key [k] appears in the domain of the map [m]. *) let mem k m = try let _ = lookup k m in true with Not_found -> false (* The auxiliary function [join] merges two trees in the simple case where their prefixes disagree. Assume $t_0$ and $t_1$ are non-empty trees, with longest common prefixes $p_0$ and $p_1$, respectively. Further, suppose that $p_0$ and $p_1$ disagree, that is, neither prefix is contained in the other. Then, no matter how large $t_0$ and $t_1$ are, we can merge them simply by creating a new [Branch] node that has $t_0$ and $t_1$ as children! *) let join p0 t0 p1 t1 = let m = X.branching_bit p0 p1 in let p = X.mask p0 (* for instance *) m in if (p0 land m) = 0 then Branch(p, m, t0, t1) else Branch(p, m, t1, t0) (* The auxiliary function [match_prefix] tells whether a given key has a given prefix. More specifically, [match_prefix k p m] returns [true] if and only if the key [k] has prefix [p] up to bit [m]. Throughout our implementation of Patricia trees, prefixes are assumed to be in normal form, i.e. their irrelevant bits are set to some predictable value. Formally, we assume [X.mask p m] equals [p] whenever [p] is a prefix with [m] relevant bits. This allows implementing [match_prefix] using only one call to [X.mask]. On the other hand, this requires normalizing prefixes, as done e.g. in [join] above, where [X.mask p0 m] has to be used instead of [p0]. *) let match_prefix k p m = X.mask k m = p (* [fine_add decide k d m] returns a map whose bindings are all bindings in [m], plus a binding of the key [k] to the datum [d]. If a binding from [k] to [d0] already exists, then the resulting map contains a binding from [k] to [decide d0 d]. *) type 'a decision = 'a -> 'a -> 'a exception Unchanged let basic_add decide k d m = let rec add t = match t with  POTTIER Francois committed Apr 28, 2016 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248  | Empty -> Leaf (k, d) | Leaf (k0, d0) -> if k = k0 then let d' = decide d0 d in if d' == d0 then raise Unchanged else Leaf (k, d') else join k (Leaf (k, d)) k0 t | Branch (p, m, t0, t1) -> if match_prefix k p m then if (k land m) = 0 then Branch (p, m, add t0, t1) else Branch (p, m, t0, add t1) else join k (Leaf (k, d)) p t in  fpottier committed Mar 01, 2013 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264  add m let strict_add k d m = basic_add (fun _ _ -> raise Unchanged) k d m let fine_add decide k d m = try basic_add decide k d m with Unchanged -> m (* [add k d m] returns a map whose bindings are all bindings in [m], plus a binding of the key [k] to the datum [d]. If a binding already exists for [k], it is overridden. *) let add k d m =  POTTIER Francois committed Dec 04, 2014 265  fine_add (fun _old_binding new_binding -> new_binding) k d m  fpottier committed Mar 01, 2013 266 267 268 269 270 271 272 273 274 275 276  (* [singleton k d] returns a map whose only binding is from [k] to [d]. *) let singleton k d = Leaf (k, d) (* [is_singleton m] returns [Some (k, d)] if [m] is a singleton map that maps [k] to [d]. Otherwise, it returns [None]. *) let is_singleton = function | Leaf (k, d) ->  POTTIER Francois committed Apr 28, 2016 277  Some (k, d)  fpottier committed Mar 01, 2013 278 279  | Empty | Branch _ ->  POTTIER Francois committed Apr 28, 2016 280  None  fpottier committed Mar 01, 2013 281 282 283 284 285  (* [is_empty m] returns [true] if and only if the map [m] defines no bindings at all. *) let is_empty = function | Empty ->  POTTIER Francois committed Apr 28, 2016 286  true  fpottier committed Mar 01, 2013 287 288  | Leaf _ | Branch _ ->  POTTIER Francois committed Apr 28, 2016 289  false  fpottier committed Mar 01, 2013 290 291 292 293 294 295  (* [cardinal m] returns [m]'s cardinal, that is, the number of keys it binds, or, in other words, its domain's cardinal. *) let rec cardinal = function | Empty ->  POTTIER Francois committed Apr 28, 2016 296  0  fpottier committed Mar 01, 2013 297  | Leaf _ ->  POTTIER Francois committed Apr 28, 2016 298  1  fpottier committed Mar 01, 2013 299  | Branch (_, _, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 300  cardinal t0 + cardinal t1  fpottier committed Mar 01, 2013 301 302 303 304 305 306 307  (* [remove k m] returns the map [m] deprived from any binding involving [k]. *) let remove key m = let rec remove = function | Empty ->  POTTIER Francois committed Apr 28, 2016 308  raise Not_found  fpottier committed Mar 01, 2013 309  | Leaf (key', _) ->  POTTIER Francois committed Apr 28, 2016 310 311 312 313  if key = key' then Empty else raise Not_found  fpottier committed Mar 01, 2013 314  | Branch (prefix, mask, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 315 316 317 318 319 320 321 322 323 324 325 326  if (key land mask) = 0 then match remove tree0 with | Empty -> tree1 | tree0 -> Branch (prefix, mask, tree0, tree1) else match remove tree1 with | Empty -> tree0 | tree1 -> Branch (prefix, mask, tree0, tree1) in  fpottier committed Mar 01, 2013 327 328 329 330 331 332 333 334 335 336 337 338  try remove m with Not_found -> m (* [lookup_and_remove k m] looks up the value [v] associated to the key [k] in the map [m], and raises [Not_found] if no value is bound to [k]. The call returns the value [v], together with the map [m] deprived from the binding from [k] to [v]. *) let rec lookup_and_remove key = function | Empty ->  POTTIER Francois committed Apr 28, 2016 339  raise Not_found  fpottier committed Mar 01, 2013 340  | Leaf (key', data) ->  POTTIER Francois committed Apr 28, 2016 341 342 343 344  if key = key' then data, Empty else raise Not_found  fpottier committed Mar 01, 2013 345  | Branch (prefix, mask, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 346 347 348 349 350 351 352 353 354 355 356 357  if (key land mask) = 0 then match lookup_and_remove key tree0 with | data, Empty -> data, tree1 | data, tree0 -> data, Branch (prefix, mask, tree0, tree1) else match lookup_and_remove key tree1 with | data, Empty -> data, tree0 | data, tree1 -> data, Branch (prefix, mask, tree0, tree1)  fpottier committed Mar 01, 2013 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375  let find_and_remove = lookup_and_remove (* [fine_union decide m1 m2] returns the union of the maps [m1] and [m2]. If a key [k] is bound to [x1] (resp. [x2]) within [m1] (resp. [m2]), then [decide] is called. It is passed [x1] and [x2], and must return the value which shall be bound to [k] in the final map. The operation returns [m2] itself (as opposed to a copy of it) when its result is equal to [m2]. *) let reverse decision elem1 elem2 = decision elem2 elem1 let fine_union decide m1 m2 = let rec union s t = match s, t with  POTTIER Francois committed Apr 28, 2016 376   POTTIER Francois committed Apr 28, 2016 377 378  | Empty, _ -> t  fpottier committed Mar 01, 2013 379  | (Leaf _ | Branch _), Empty ->  POTTIER Francois committed Apr 28, 2016 380  s  fpottier committed Mar 01, 2013 381 382  | Leaf(key, value), _ ->  POTTIER Francois committed Apr 28, 2016 383  fine_add (reverse decide) key value t  fpottier committed Mar 01, 2013 384  | Branch _, Leaf(key, value) ->  POTTIER Francois committed Apr 28, 2016 385  fine_add decide key value s  fpottier committed Mar 01, 2013 386 387  | Branch(p, m, s0, s1), Branch(q, n, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 388  if (p = q) && (m = n) then  fpottier committed Mar 01, 2013 389   POTTIER Francois committed Apr 28, 2016 390  (* The trees have the same prefix. Merge their sub-trees. *)  fpottier committed Mar 01, 2013 391   POTTIER Francois committed Apr 28, 2016 392 393 394 395  let u0 = union s0 t0 and u1 = union s1 t1 in if t0 == u0 && t1 == u1 then t else Branch(p, m, u0, u1)  fpottier committed Mar 01, 2013 396   POTTIER Francois committed Apr 28, 2016 397  else if (X.shorter m n) && (match_prefix q p m) then  fpottier committed Mar 01, 2013 398   POTTIER Francois committed Apr 28, 2016 399  (* [q] contains [p]. Merge [t] with a sub-tree of [s]. *)  fpottier committed Mar 01, 2013 400   POTTIER Francois committed Apr 28, 2016 401 402 403 404  if (q land m) = 0 then Branch(p, m, union s0 t, s1) else Branch(p, m, s0, union s1 t)  fpottier committed Mar 01, 2013 405   POTTIER Francois committed Apr 28, 2016 406  else if (X.shorter n m) && (match_prefix p q n) then  fpottier committed Mar 01, 2013 407   POTTIER Francois committed Apr 28, 2016 408  (* [p] contains [q]. Merge [s] with a sub-tree of [t]. *)  fpottier committed Mar 01, 2013 409   POTTIER Francois committed Apr 28, 2016 410 411 412 413 414 415 416 417  if (p land n) = 0 then let u0 = union s t0 in if t0 == u0 then t else Branch(q, n, u0, t1) else let u1 = union s t1 in if t1 == u1 then t else Branch(q, n, t0, u1)  fpottier committed Mar 01, 2013 418   POTTIER Francois committed Apr 28, 2016 419  else  fpottier committed Mar 01, 2013 420   POTTIER Francois committed Apr 28, 2016 421  (* The prefixes disagree. *)  fpottier committed Mar 01, 2013 422   POTTIER Francois committed Apr 28, 2016 423  join p s q t in  fpottier committed Mar 01, 2013 424 425 426 427 428 429 430  union m1 m2 (* [union m1 m2] returns the union of the maps [m1] and [m2]. Bindings in [m2] take precedence over those in [m1]. *) let union m1 m2 =  POTTIER Francois committed Dec 04, 2014 431  fine_union (fun _d d' -> d') m1 m2  fpottier committed Mar 01, 2013 432 433 434 435 436 437  (* [iter f m] invokes [f k x], in turn, for each binding from key [k] to element [x] in the map [m]. Keys are presented to [f] according to some unspecified, but fixed, order. *) let rec iter f = function | Empty ->  POTTIER Francois committed Apr 28, 2016 438  ()  fpottier committed Mar 01, 2013 439  | Leaf (key, data) ->  POTTIER Francois committed Apr 28, 2016 440  f key data  fpottier committed Mar 01, 2013 441  | Branch (_, _, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 442 443  iter f tree0; iter f tree1  fpottier committed Mar 01, 2013 444 445 446 447 448 449 450 451 452  (* [fold f m seed] invokes [f k d accu], in turn, for each binding from key [k] to datum [d] in the map [m]. Keys are presented to [f] in increasing order according to the map's ordering. The initial value of [accu] is [seed]; then, at each new call, its value is the value returned by the previous invocation of [f]. The value returned by [fold] is the final value of [accu]. *) let rec fold f m accu = match m with | Empty ->  POTTIER Francois committed Apr 28, 2016 453  accu  fpottier committed Mar 01, 2013 454  | Leaf (key, data) ->  POTTIER Francois committed Apr 28, 2016 455  f key data accu  fpottier committed Mar 01, 2013 456  | Branch (_, _, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 457  fold f tree1 (fold f tree0 accu)  fpottier committed Mar 01, 2013 458 459 460 461 462 463  (* [fold_rev] performs exactly the same job as [fold], but presents keys to [f] in the opposite order. *) let rec fold_rev f m accu = match m with | Empty ->  POTTIER Francois committed Apr 28, 2016 464  accu  fpottier committed Mar 01, 2013 465  | Leaf (key, data) ->  POTTIER Francois committed Apr 28, 2016 466  f key data accu  fpottier committed Mar 01, 2013 467  | Branch (_, _, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 468  fold_rev f tree0 (fold_rev f tree1 accu)  fpottier committed Mar 01, 2013 469 470 471 472 473 474 475 476  (* It is valid to evaluate [iter2 f m1 m2] if and only if [m1] and [m2] have the same domain. Doing so invokes [f k x1 x2], in turn, for each key [k] bound to [x1] in [m1] and to [x2] in [m2]. Bindings are presented to [f] according to some unspecified, but fixed, order. *) let rec iter2 f t1 t2 = match t1, t2 with | Empty, Empty ->  POTTIER Francois committed Apr 28, 2016 477  ()  fpottier committed Mar 01, 2013 478  | Leaf (key1, data1), Leaf (key2, data2) ->  POTTIER Francois committed Apr 28, 2016 479 480  assert (key1 = key2); f key1 (* for instance *) data1 data2  fpottier committed Mar 01, 2013 481  | Branch (p1, m1, left1, right1), Branch (p2, m2, left2, right2) ->  POTTIER Francois committed Apr 28, 2016 482 483 484 485  assert (p1 = p2); assert (m1 = m2); iter2 f left1 left2; iter2 f right1 right2  fpottier committed Mar 01, 2013 486  | _, _ ->  POTTIER Francois committed Apr 28, 2016 487  assert false  fpottier committed Mar 01, 2013 488 489 490 491 492 493  (* [map f m] returns the map obtained by composing the map [m] with the function [f]; that is, the map $k\mapsto f(m(k))$. *) let rec map f = function | Empty ->  POTTIER Francois committed Apr 28, 2016 494  Empty  fpottier committed Mar 01, 2013 495  | Leaf (key, data) ->  POTTIER Francois committed Apr 28, 2016 496  Leaf(key, f data)  fpottier committed Mar 01, 2013 497  | Branch (p, m, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 498  Branch (p, m, map f tree0, map f tree1)  fpottier committed Mar 01, 2013 499 500 501 502 503 504 505  (* [endo_map] is similar to [map], but attempts to physically share its result with its input. This saves memory when [f] is the identity function. *) let rec endo_map f tree = match tree with | Empty ->  POTTIER Francois committed Apr 28, 2016 506  tree  fpottier committed Mar 01, 2013 507  | Leaf (key, data) ->  POTTIER Francois committed Apr 28, 2016 508 509 510 511 512  let data' = f data in if data == data' then tree else Leaf(key, data')  fpottier committed Mar 01, 2013 513  | Branch (p, m, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 514 515 516 517 518 519  let tree0' = endo_map f tree0 in let tree1' = endo_map f tree1 in if (tree0' == tree0) && (tree1' == tree1) then tree else Branch (p, m, tree0', tree1')  fpottier committed Mar 01, 2013 520   POTTIER Francois committed Oct 20, 2015 521 522 523 524 525 526 527 528 529 530 531  (* [filter f m] returns a copy of the map [m] where only the bindings that satisfy [f] have been retained. *) let filter f m = fold (fun key data accu -> if f key data then add key data accu else accu ) m empty  fpottier committed Mar 01, 2013 532 533 534 535 536 537 538 539 540 541 542  (* [iterator m] returns a stateful iterator over the map [m]. *) (* TEMPORARY performance could be improved, see JCF's paper *) let iterator m = let remainder = ref [ m ] in let rec next () = match !remainder with | [] ->  POTTIER Francois committed Apr 28, 2016 543  None  fpottier committed Mar 01, 2013 544  | Empty :: parent ->  POTTIER Francois committed Apr 28, 2016 545 546  remainder := parent; next()  fpottier committed Mar 01, 2013 547  | (Leaf (key, data)) :: parent ->  POTTIER Francois committed Apr 28, 2016 548 549  remainder := parent; Some (key, data)  fpottier committed Mar 01, 2013 550  | (Branch(_, _, s0, s1)) :: parent ->  POTTIER Francois committed Apr 28, 2016 551 552  remainder := s0 :: s1 :: parent; next () in  fpottier committed Mar 01, 2013 553 554 555 556 557 558 559 560 561 562 563 564  next (* If [dcompare] is an ordering over data, then [compare dcompare] is an ordering over maps. *) exception Got of int let compare dcompare m1 m2 = let iterator2 = iterator m2 in try iter (fun key1 data1 ->  POTTIER Francois committed Apr 28, 2016 565 566 567 568 569 570 571 572 573 574 575  match iterator2() with | None -> raise (Got 1) | Some (key2, data2) -> let c = Pervasives.compare key1 key2 in if c <> 0 then raise (Got c) else let c = dcompare data1 data2 in if c <> 0 then raise (Got c)  fpottier committed Mar 01, 2013 576 577 578  ) m1; match iterator2() with | None ->  POTTIER Francois committed Apr 28, 2016 579  0  fpottier committed Mar 01, 2013 580  | Some _ ->  POTTIER Francois committed Apr 28, 2016 581  -1  fpottier committed Mar 01, 2013 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609  with Got c -> c (*i --------------------------------------------------------------------------------------------------------------- i*) (*s \mysection{Patricia-tree-based sets} *) (* To enhance code sharing, it would be possible to implement maps as sets of pairs, or (vice-versa) to implement sets as maps to the unit element. However, both possibilities introduce some space and time inefficiency. To avoid it, we define each structure separately. *) module Domain = struct type element = int type t = | Empty | Leaf of int | Branch of int * X.mask * t * t (* The empty set. *) let empty = Empty (* [is_empty s] returns [true] if and only if the set [s] is empty. *) let is_empty = function | Empty ->  POTTIER Francois committed Apr 28, 2016 610  true  fpottier committed Mar 01, 2013 611 612  | Leaf _ | Branch _ ->  POTTIER Francois committed Apr 28, 2016 613  false  fpottier committed Mar 01, 2013 614 615 616 617 618 619  (* [singleton x] returns a set whose only element is [x]. *) let singleton x = Leaf x  POTTIER Francois committed Jul 07, 2015 620 621 622 623 624 625 626 627 628  (* [is_singleton s] tests whether [s] is a singleton set. *) let is_singleton = function | Leaf _ -> true | Empty | Branch _ -> false  fpottier committed Mar 01, 2013 629 630 631 632 633  (* [choose s] returns an arbitrarily chosen element of [s], if [s] is nonempty, and raises [Not_found] otherwise. *) let rec choose = function | Empty ->  POTTIER Francois committed Apr 28, 2016 634  raise Not_found  fpottier committed Mar 01, 2013 635  | Leaf x ->  POTTIER Francois committed Apr 28, 2016 636  x  fpottier committed Mar 01, 2013 637  | Branch (_, _, tree0, _) ->  POTTIER Francois committed Apr 28, 2016 638  choose tree0  fpottier committed Mar 01, 2013 639 640 641 642 643  (* [cardinal s] returns [s]'s cardinal. *) let rec cardinal = function | Empty ->  POTTIER Francois committed Apr 28, 2016 644  0  fpottier committed Mar 01, 2013 645  | Leaf _ ->  POTTIER Francois committed Apr 28, 2016 646  1  fpottier committed Mar 01, 2013 647  | Branch (_, _, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 648  cardinal t0 + cardinal t1  fpottier committed Mar 01, 2013 649 650 651 652 653  (* [mem x s] returns [true] if and only if [x] appears in the set [s]. *) let rec mem x = function | Empty ->  POTTIER Francois committed Apr 28, 2016 654  false  fpottier committed Mar 01, 2013 655  | Leaf x' ->  POTTIER Francois committed Apr 28, 2016 656  x = x'  fpottier committed Mar 01, 2013 657  | Branch (_, mask, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 658  mem x (if (x land mask) = 0 then tree0 else tree1)  fpottier committed Mar 01, 2013 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676  (* The auxiliary function [join] merges two trees in the simple case where their prefixes disagree. *) let join p0 t0 p1 t1 = let m = X.branching_bit p0 p1 in let p = X.mask p0 (* for instance *) m in if (p0 land m) = 0 then Branch(p, m, t0, t1) else Branch(p, m, t1, t0) (* [add x s] returns a set whose elements are all elements of [s], plus [x]. *) exception Unchanged let rec strict_add x t = match t with | Empty ->  POTTIER Francois committed Apr 28, 2016 677  Leaf x  fpottier committed Mar 01, 2013 678  | Leaf x0 ->  POTTIER Francois committed Apr 28, 2016 679 680 681 682  if x = x0 then raise Unchanged else join x (Leaf x) x0 t  fpottier committed Mar 01, 2013 683  | Branch (p, m, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 684 685 686 687 688  if match_prefix x p m then if (x land m) = 0 then Branch (p, m, strict_add x t0, t1) else Branch (p, m, t0, strict_add x t1) else join x (Leaf x) p t  fpottier committed Mar 01, 2013 689 690 691 692 693 694 695 696 697 698 699 700 701  let add x s = try strict_add x s with Unchanged -> s (* [remove x s] returns a set whose elements are all elements of [s], except [x]. *) let remove x s = let rec strict_remove = function | Empty ->  POTTIER Francois committed Apr 28, 2016 702  raise Not_found  fpottier committed Mar 01, 2013 703  | Leaf x' ->  POTTIER Francois committed Apr 28, 2016 704 705 706 707  if x = x' then Empty else raise Not_found  fpottier committed Mar 01, 2013 708  | Branch (prefix, mask, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 709 710 711 712 713 714 715 716 717 718 719 720  if (x land mask) = 0 then match strict_remove tree0 with | Empty -> tree1 | tree0 -> Branch (prefix, mask, tree0, tree1) else match strict_remove tree1 with | Empty -> tree0 | tree1 -> Branch (prefix, mask, tree0, tree1) in  fpottier committed Mar 01, 2013 721 722 723 724 725 726 727 728 729 730 731 732  try strict_remove s with Not_found -> s (* [union s1 s2] returns the union of the sets [s1] and [s2]. *) let rec union s t = match s, t with | Empty, _ ->  POTTIER Francois committed Apr 28, 2016 733  t  fpottier committed Mar 01, 2013 734  | _, Empty ->  POTTIER Francois committed Apr 28, 2016 735  s  fpottier committed Mar 01, 2013 736 737  | Leaf x, _ ->  POTTIER Francois committed Apr 28, 2016 738  add x t  fpottier committed Mar 01, 2013 739  | _, Leaf x ->  POTTIER Francois committed Apr 28, 2016 740  add x s  fpottier committed Mar 01, 2013 741 742  | Branch(p, m, s0, s1), Branch(q, n, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 743  if (p = q) && (m = n) then  fpottier committed Mar 01, 2013 744   POTTIER Francois committed Apr 28, 2016 745  (* The trees have the same prefix. Merge their sub-trees. *)  fpottier committed Mar 01, 2013 746   POTTIER Francois committed Apr 28, 2016 747 748 749 750  let u0 = union s0 t0 and u1 = union s1 t1 in if t0 == u0 && t1 == u1 then t else Branch(p, m, u0, u1)  fpottier committed Mar 01, 2013 751   POTTIER Francois committed Apr 28, 2016 752  else if (X.shorter m n) && (match_prefix q p m) then  fpottier committed Mar 01, 2013 753   POTTIER Francois committed Apr 28, 2016 754  (* [q] contains [p]. Merge [t] with a sub-tree of [s]. *)  fpottier committed Mar 01, 2013 755   POTTIER Francois committed Apr 28, 2016 756 757 758 759  if (q land m) = 0 then Branch(p, m, union s0 t, s1) else Branch(p, m, s0, union s1 t)  fpottier committed Mar 01, 2013 760   POTTIER Francois committed Apr 28, 2016 761  else if (X.shorter n m) && (match_prefix p q n) then  fpottier committed Mar 01, 2013 762   POTTIER Francois committed Apr 28, 2016 763  (* [p] contains [q]. Merge [s] with a sub-tree of [t]. *)  fpottier committed Mar 01, 2013 764   POTTIER Francois committed Apr 28, 2016 765 766 767 768 769 770 771 772  if (p land n) = 0 then let u0 = union s t0 in if t0 == u0 then t else Branch(q, n, u0, t1) else let u1 = union s t1 in if t1 == u1 then t else Branch(q, n, t0, u1)  fpottier committed Mar 01, 2013 773   POTTIER Francois committed Apr 28, 2016 774  else  fpottier committed Mar 01, 2013 775   POTTIER Francois committed Apr 28, 2016 776  (* The prefixes disagree. *)  fpottier committed Mar 01, 2013 777   POTTIER Francois committed Apr 28, 2016 778  join p s q t  fpottier committed Mar 01, 2013 779 780 781 782 783 784  (* [build] is a smart constructor''. It builds a [Branch] node with the specified arguments, but ensures that the newly created node does not have an [Empty] child. *) let build p m t0 t1 = match t0, t1 with  POTTIER Francois committed Apr 28, 2016 785 786 787 788 789 790 791 792  | Empty, Empty -> Empty | Empty, _ -> t1 | _, Empty -> t0 | _, _ -> Branch(p, m, t0, t1)  fpottier committed Mar 01, 2013 793 794 795 796 797 798 799 800  (* [inter s t] returns the set intersection of [s] and [t], that is, $s\cap t$. *) let rec inter s t = match s, t with | Empty, _ | _, Empty ->  POTTIER Francois committed Apr 28, 2016 801  Empty  fpottier committed Mar 01, 2013 802 803 804  | (Leaf x as s), t | t, (Leaf x as s) ->  POTTIER Francois committed Apr 28, 2016 805  if mem x t then s else Empty  fpottier committed Mar 01, 2013 806 807  | Branch(p, m, s0, s1), Branch(q, n, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 808  if (p = q) && (m = n) then  fpottier committed Mar 01, 2013 809   POTTIER Francois committed Apr 28, 2016 810  (* The trees have the same prefix. Compute the intersections of their sub-trees. *)  fpottier committed Mar 01, 2013 811   POTTIER Francois committed Apr 28, 2016 812  build p m (inter s0 t0) (inter s1 t1)  fpottier committed Mar 01, 2013 813   POTTIER Francois committed Apr 28, 2016 814  else if (X.shorter m n) && (match_prefix q p m) then  fpottier committed Mar 01, 2013 815   POTTIER Francois committed Apr 28, 2016 816  (* [q] contains [p]. Intersect [t] with a sub-tree of [s]. *)  fpottier committed Mar 01, 2013 817   POTTIER Francois committed Apr 28, 2016 818  inter (if (q land m) = 0 then s0 else s1) t  fpottier committed Mar 01, 2013 819   POTTIER Francois committed Apr 28, 2016 820  else if (X.shorter n m) && (match_prefix p q n) then  fpottier committed Mar 01, 2013 821   POTTIER Francois committed Apr 28, 2016 822  (* [p] contains [q]. Intersect [s] with a sub-tree of [t]. *)  fpottier committed Mar 01, 2013 823   POTTIER Francois committed Apr 28, 2016 824  inter s (if (p land n) = 0 then t0 else t1)  fpottier committed Mar 01, 2013 825   POTTIER Francois committed Apr 28, 2016 826  else  fpottier committed Mar 01, 2013 827   POTTIER Francois committed Apr 28, 2016 828  (* The prefixes disagree. *)  fpottier committed Mar 01, 2013 829   POTTIER Francois committed Apr 28, 2016 830  Empty  fpottier committed Mar 01, 2013 831 832 833 834 835 836 837 838 839 840 841 842 843  (* [disjoint s1 s2] returns [true] if and only if the sets [s1] and [s2] are disjoint, i.e. iff their intersection is empty. It is a specialized version of [inter], which uses less space. *) exception NotDisjoint let disjoint s t = let rec inter s t = match s, t with | Empty, _ | _, Empty ->  POTTIER Francois committed Apr 28, 2016 844  ()  fpottier committed Mar 01, 2013 845 846  | Leaf x, _ ->  POTTIER Francois committed Apr 28, 2016 847 848  if mem x t then raise NotDisjoint  fpottier committed Mar 01, 2013 849  | _, Leaf x ->  POTTIER Francois committed Apr 28, 2016 850 851  if mem x s then raise NotDisjoint  fpottier committed Mar 01, 2013 852 853  | Branch(p, m, s0, s1), Branch(q, n, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 854 855 856 857 858 859 860 861 862 863  if (p = q) && (m = n) then begin inter s0 t0; inter s1 t1 end else if (X.shorter m n) && (match_prefix q p m) then inter (if (q land m) = 0 then s0 else s1) t else if (X.shorter n m) && (match_prefix p q n) then inter s (if (p land n) = 0 then t0 else t1) else () in  fpottier committed Mar 01, 2013 864 865 866 867 868 869 870 871 872 873 874 875  try inter s t; true with NotDisjoint -> false (* [iter f s] invokes [f x], in turn, for each element [x] of the set [s]. Elements are presented to [f] according to some unspecified, but fixed, order. *) let rec iter f = function | Empty ->  POTTIER Francois committed Apr 28, 2016 876  ()  fpottier committed Mar 01, 2013 877  | Leaf x ->  POTTIER Francois committed Apr 28, 2016 878  f x  fpottier committed Mar 01, 2013 879  | Branch (_, _, tree0, tree1) ->  POTTIER Francois committed Apr 28, 2016 880 881  iter f tree0; iter f tree1  fpottier committed Mar 01, 2013 882 883 884 885 886 887 888 889 890  (* [fold f s seed] invokes [f x accu], in turn, for each element [x] of the set [s]. Elements are presented to [f] according to some unspecified, but fixed, order. The initial value of [accu] is [seed]; then, at each new call, its value is the value returned by the previous invocation of [f]. The value returned by [fold] is the final value of [accu]. In other words, if $s = \{ x_1, x_2, \ldots, x_n \}$, where $x_1 < x_2 < \ldots < x_n$, then [fold f s seed] computes $([f]\,x_n\,\ldots\,([f]\,x_2\,([f]\,x_1\,[seed]))\ldots)$. *) let rec fold f s accu = match s with  POTTIER Francois committed Apr 28, 2016 891 892 893 894 895 896  | Empty -> accu | Leaf x -> f x accu | Branch (_, _, s0, s1) -> fold f s1 (fold f s0 accu)  fpottier committed Mar 01, 2013 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916  (* [elements s] is a list of all elements in the set [s]. *) let elements s = fold (fun tl hd -> tl :: hd) s [] (* [iterator s] returns a stateful iterator over the set [s]. That is, if $s = \{ x_1, x_2, \ldots, x_n \}$, where $x_1 < x_2 < \ldots < x_n$, then [iterator s] is a function which, when invoked for the $k^{\text{th}}$ time, returns [Some]$x_k$, if $k\leq n$, and [None] otherwise. Such a function can be useful when one wishes to iterate over a set's elements, without being restricted by the call stack's discipline. For more comments about this algorithm, please see module [Baltree], which defines a similar one. *) let iterator s = let remainder = ref [ s ] in let rec next () = match !remainder with | [] ->  POTTIER Francois committed Apr 28, 2016 917  None  fpottier committed Mar 01, 2013 918  | Empty :: parent ->  POTTIER Francois committed Apr 28, 2016 919 920  remainder := parent; next()  fpottier committed Mar 01, 2013 921  | (Leaf x) :: parent ->  POTTIER Francois committed Apr 28, 2016 922 923  remainder := parent; Some x  fpottier committed Mar 01, 2013 924  | (Branch(_, _, s0, s1)) :: parent ->  POTTIER Francois committed Apr 28, 2016 925 926  remainder := s0 :: s1 :: parent; next () in  fpottier committed Mar 01, 2013 927 928 929 930 931 932 933 934 935 936 937  next (* [compare] is an ordering over sets. *) exception Got of int let compare s1 s2 = let iterator2 = iterator s2 in try iter (fun x1 ->  POTTIER Francois committed Apr 28, 2016 938 939 940 941 942 943 944  match iterator2() with | None -> raise (Got 1) | Some x2 -> let c = Pervasives.compare x1 x2 in if c <> 0 then raise (Got c)  fpottier committed Mar 01, 2013 945 946 947  ) s1; match iterator2() with | None ->  POTTIER Francois committed Apr 28, 2016 948  0  fpottier committed Mar 01, 2013 949  | Some _ ->  POTTIER Francois committed Apr 28, 2016 950  -1  fpottier committed Mar 01, 2013 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969  with Got c -> c (* [equal] implements equality over sets. *) let equal s1 s2 = compare s1 s2 = 0 (* [subset] implements the subset predicate over sets. In other words, [subset s t] returns [true] if and only if $s\subseteq t$. It is a specialized version of [diff]. *) exception NotSubset let subset s t = let rec diff s t = match s, t with | Empty, _ ->  POTTIER Francois committed Apr 28, 2016 970  ()  fpottier committed Mar 01, 2013 971 972 973  | _, Empty | Branch _, Leaf _ ->  POTTIER Francois committed Apr 28, 2016 974  raise NotSubset  fpottier committed Mar 01, 2013 975  | Leaf x, _ ->  POTTIER Francois committed Apr 28, 2016 976 977  if not (mem x t) then raise NotSubset  fpottier committed Mar 01, 2013 978 979 980  | Branch(p, m, s0, s1), Branch(q, n, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 981  if (p = q) && (m = n) then begin  fpottier committed Mar 01, 2013 982   POTTIER Francois committed Apr 28, 2016 983 984  diff s0 t0; diff s1 t1  fpottier committed Mar 01, 2013 985   POTTIER Francois committed Apr 28, 2016 986 987  end else if (X.shorter n m) && (match_prefix p q n) then  fpottier committed Mar 01, 2013 988   POTTIER Francois committed Apr 28, 2016 989  diff s (if (p land n) = 0 then t0 else t1)  fpottier committed Mar 01, 2013 990   POTTIER Francois committed Apr 28, 2016 991  else  fpottier committed Mar 01, 2013 992   POTTIER Francois committed Apr 28, 2016 993 994  (* Either [q] contains [p], which means at least one of [s]'s sub-trees is not contained within [t], or the prefixes disagree. In either case, the subset relationship cannot possibly hold. *)  fpottier committed Mar 01, 2013 995   POTTIER Francois committed Apr 28, 2016 996  raise NotSubset in  fpottier committed Mar 01, 2013 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010  try diff s t; true with NotSubset -> false end (*i --------------------------------------------------------------------------------------------------------------- i*) (*s \mysection{Relating sets and maps} *) (* Back to the world of maps. Let us now describe the relationship which exists between maps and their domains. *)  POTTIER Francois committed Apr 28, 2016 1011  (* [domain m] returns [m]'s domain. *)  fpottier committed Mar 01, 2013 1012 1013 1014  let rec domain = function | Empty ->  POTTIER Francois committed Apr 28, 2016 1015  Domain.Empty  fpottier committed Mar 01, 2013 1016  | Leaf (k, _) ->  POTTIER Francois committed Apr 28, 2016 1017  Domain.Leaf k  fpottier committed Mar 01, 2013 1018  | Branch (p, m, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 1019  Domain.Branch (p, m, domain t0, domain t1)  fpottier committed Mar 01, 2013 1020 1021 1022 1023 1024  (* [lift f s] returns the map $k\mapsto f(k)$, where $k$ ranges over a set of keys [s]. *) let rec lift f = function | Domain.Empty ->  POTTIER Francois committed Apr 28, 2016 1025  Empty  fpottier committed Mar 01, 2013 1026  | Domain.Leaf k ->  POTTIER Francois committed Apr 28, 2016 1027  Leaf (k, f k)  fpottier committed Mar 01, 2013 1028  | Domain.Branch (p, m, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 1029  Branch(p, m, lift f t0, lift f t1)  fpottier committed Mar 01, 2013 1030 1031 1032 1033 1034 1035 1036  (* [build] is a smart constructor''. It builds a [Branch] node with the specified arguments, but ensures that the newly created node does not have an [Empty] child. *) let build p m t0 t1 = match t0, t1 with | Empty, Empty ->  POTTIER Francois committed Apr 28, 2016 1037  Empty  fpottier committed Mar 01, 2013 1038  | Empty, _ ->  POTTIER Francois committed Apr 28, 2016 1039  t1  fpottier committed Mar 01, 2013 1040  | _, Empty ->  POTTIER Francois committed Apr 28, 2016 1041  t0  fpottier committed Mar 01, 2013 1042  | _, _ ->  POTTIER Francois committed Apr 28, 2016 1043  Branch(p, m, t0, t1)  fpottier committed Mar 01, 2013 1044 1045 1046 1047 1048 1049 1050 1051  (* [corestrict m d] performs a co-restriction of the map [m] to the domain [d]. That is, it returns the map $k\mapsto m(k)$, where $k$ ranges over all keys bound in [m] but \emph{not} present in [d]. Its code resembles [diff]'s. *) let rec corestrict s t = match s, t with  POTTIER Francois committed Apr 28, 2016 1052 1053 1054  | Empty, _ | _, Domain.Empty -> s  fpottier committed Mar 01, 2013 1055   POTTIER Francois committed Apr 28, 2016 1056 1057 1058 1059  | Leaf (k, _), _ -> if Domain.mem k t then Empty else s | _, Domain.Leaf k -> remove k s  POTTIER Francois committed Apr 28, 2016 1060   fpottier committed Mar 01, 2013 1061  | Branch(p, m, s0, s1), Domain.Branch(q, n, t0, t1) ->  POTTIER Francois committed Apr 28, 2016 1062  if (p = q) && (m = n) then  fpottier committed Mar 01, 2013 1063   POTTIER Francois committed Apr 28, 2016 1064  build p m (corestrict s0 t0) (corestrict s1 t1)  fpottier committed Mar 01, 2013 1065   POTTIER Francois committed Apr 28, 2016 1066  else if (X.shorter m n) && (match_prefix q p m) then  fpottier committed Mar 01, 2013 1067   POTTIER Francois committed Apr 28, 2016 1068 1069 1070 1071  if (q land m) = 0 then build p m (corestrict s0 t) s1 else build p m s0 (corestrict s1 t)  fpottier committed Mar 01, 2013 1072   POTTIER Francois committed Apr 28, 2016 1073  else if (X.shorter n m) && (match_prefix p q n) then  fpottier committed Mar 01, 2013 1074   POTTIER Francois committed Apr 28, 2016 1075  corestrict s (if (p land n) = 0 then t0 else t1)  fpottier committed Mar 01, 2013 1076   POTTIER Francois committed Apr 28, 2016 1077  else  fpottier committed Mar 01, 2013 1078   POTTIER Francois committed Apr 28, 2016 1079  s  fpottier committed Mar 01, 2013 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089  end (*i --------------------------------------------------------------------------------------------------------------- i*) (*s \mysection{Instantiating the functor} *) module Little = Make(Endianness.Little) module Big = Make(Endianness.Big)