patricia.ml 31.9 KB
Newer Older
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.                                                             *)
(*                                                                            *)
(******************************************************************************)

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
93
        m
94
      else
95
        highest_bit (x - m)
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 ->
155
        raise Not_found
156
    | Leaf (key, data) ->
157
        key, data
158
    | Branch (_, _, tree0, _) ->
159
        choose tree0
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 ->
171
        raise Not_found
172
    | Leaf (key', data) ->
173 174 175 176
        if key = key' then
          data
        else
          raise Not_found
177
    | Branch (_, mask, tree0, tree1) ->
178
        lookup key (if (key land mask) = 0 then tree0 else tree1)
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
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
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 =
265
    fine_add (fun _old_binding new_binding -> new_binding) k d m
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) ->
277
        Some (k, d)
278 279
    | Empty
    | Branch _ ->
280
        None
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 ->
286
        true
287 288
    | Leaf _
    | Branch _ ->
289
        false
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 ->
296
        0
297
    | Leaf _ ->
298
        1
299
    | Branch (_, _, t0, t1) ->
300
        cardinal t0 + cardinal t1
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 ->
308
          raise Not_found
309
      | Leaf (key', _) ->
310 311 312 313
          if key = key' then
            Empty
          else
            raise Not_found
314
      | Branch (prefix, mask, tree0, tree1) ->
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
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 ->
339
        raise Not_found
340
    | Leaf (key', data) ->
341 342 343 344
        if key = key' then
          data, Empty
        else
          raise Not_found
345
    | Branch (prefix, mask, tree0, tree1) ->
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)
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
376

377 378
      | Empty, _ ->
          t
379
      | (Leaf _ | Branch _), Empty ->
380
          s
381 382

      | Leaf(key, value), _ ->
383
          fine_add (reverse decide) key value t
384
      | Branch _, Leaf(key, value) ->
385
          fine_add decide key value s
386 387

      | Branch(p, m, s0, s1), Branch(q, n, t0, t1) ->
388
          if (p = q) && (m = n) then
389

390
            (* The trees have the same prefix. Merge their sub-trees. *)
391

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)
396

397
          else if (X.shorter m n) && (match_prefix q p m) then
398

399
            (* [q] contains [p]. Merge [t] with a sub-tree of [s]. *)
400

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)
405

406
          else if (X.shorter n m) && (match_prefix p q n) then
407

408
            (* [p] contains [q]. Merge [s] with a sub-tree of [t]. *)
409

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)
418

419
          else
420

421
            (* The prefixes disagree. *)
422

423
            join p s q t in
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 =
431
    fine_union (fun _d d' -> d') m1 m2
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 ->
438
        ()
439
    | Leaf (key, data) ->
440
        f key data
441
    | Branch (_, _, tree0, tree1) ->
442 443
        iter f tree0;
        iter f tree1
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 ->
453
        accu
454
    | Leaf (key, data) ->
455
        f key data accu
456
    | Branch (_, _, tree0, tree1) ->
457
        fold f tree1 (fold f tree0 accu)
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 ->
464
        accu
465
    | Leaf (key, data) ->
466
        f key data accu
467
    | Branch (_, _, tree0, tree1) ->
468
        fold_rev f tree0 (fold_rev f tree1 accu)
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 ->
477
        ()
478
    | Leaf (key1, data1), Leaf (key2, data2) ->
479 480
        assert (key1 = key2);
        f key1 (* for instance *) data1 data2
481
    | Branch (p1, m1, left1, right1), Branch (p2, m2, left2, right2) ->
482 483 484 485
        assert (p1 = p2);
        assert (m1 = m2);
        iter2 f left1 left2;
        iter2 f right1 right2
486
    | _, _ ->
487
        assert false
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 ->
494
        Empty
495
    | Leaf (key, data) ->
496
        Leaf(key, f data)
497
    | Branch (p, m, tree0, tree1) ->
498
        Branch (p, m, map f tree0, map f tree1)
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 ->
506
        tree
507
    | Leaf (key, data) ->
508 509 510 511 512
        let data' = f data in
        if data == data' then
          tree
        else
          Leaf(key, data')
513
    | Branch (p, m, tree0, tree1) ->
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')
520

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

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
      | [] ->
543
          None
544
      | Empty :: parent ->
545 546
          remainder := parent;
          next()
547
      | (Leaf (key, data)) :: parent ->
548 549
          remainder := parent;
          Some (key, data)
550
      | (Branch(_, _, s0, s1)) :: parent ->
551 552
          remainder := s0 :: s1 :: parent;
          next () in
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 ->
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)
576 577 578
      ) m1;
      match iterator2() with
      | None ->
579
          0
580
      | Some _ ->
581
          -1
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 ->
610
        true
611 612
    | Leaf _
    | Branch _ ->
613
        false
614 615 616 617 618 619

  (* [singleton x] returns a set whose only element is [x]. *)

  let singleton x =
    Leaf x

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

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 ->
634
        raise Not_found
635
    | Leaf x ->
636
        x
637
    | Branch (_, _, tree0, _) ->
638
        choose tree0
639 640 641 642 643

  (* [cardinal s] returns [s]'s cardinal. *)

  let rec cardinal = function
    | Empty ->
644
        0
645
    | Leaf _ ->
646
        1
647
    | Branch (_, _, t0, t1) ->
648
        cardinal t0 + cardinal t1
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 ->
654
        false
655
    | Leaf x' ->
656
        x = x'
657
    | Branch (_, mask, tree0, tree1) ->
658
        mem x (if (x land mask) = 0 then tree0 else tree1)
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 ->
677
        Leaf x
678
    | Leaf x0 ->
679 680 681 682
        if x = x0 then
          raise Unchanged
        else
          join x (Leaf x) x0 t
683
    | Branch (p, m, t0, t1) ->
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
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 ->
702
          raise Not_found
703
      | Leaf x' ->
704 705 706 707
        if x = x' then
          Empty
        else
          raise Not_found
708
      | Branch (prefix, mask, tree0, tree1) ->
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
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, _ ->
733
        t
734
    | _, Empty ->
735
        s
736 737

    | Leaf x, _ ->
738
        add x t
739
    | _, Leaf x ->
740
        add x s
741 742

    | Branch(p, m, s0, s1), Branch(q, n, t0, t1) ->
743
        if (p = q) && (m = n) then
744

745
          (* The trees have the same prefix. Merge their sub-trees. *)
746

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)
751

752
        else if (X.shorter m n) && (match_prefix q p m) then
753

754
          (* [q] contains [p]. Merge [t] with a sub-tree of [s]. *)
755

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)
760

761
        else if (X.shorter n m) && (match_prefix p q n) then
762

763
          (* [p] contains [q]. Merge [s] with a sub-tree of [t]. *)
764

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)
773

774
        else
775

776
          (* The prefixes disagree. *)
777

778
          join p s q t
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
785 786 787 788 789 790 791 792
    |   Empty, Empty ->
        Empty
    |   Empty, _ ->
        t1
    |   _, Empty ->
        t0
    |   _, _ ->
        Branch(p, m, t0, t1)
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 ->
801
        Empty
802 803 804

    | (Leaf x as s), t
    | t, (Leaf x as s) ->
805
        if mem x t then s else Empty
806 807

    | Branch(p, m, s0, s1), Branch(q, n, t0, t1) ->
808
        if (p = q) && (m = n) then
809

810
          (* The trees have the same prefix. Compute the intersections of their sub-trees. *)
811

812
          build p m (inter s0 t0) (inter s1 t1)
813

814
        else if (X.shorter m n) && (match_prefix q p m) then
815

816
          (* [q] contains [p]. Intersect [t] with a sub-tree of [s]. *)
817

818
          inter (if (q land m) = 0 then s0 else s1) t
819

820
        else if (X.shorter n m) && (match_prefix p q n) then
821

822
          (* [p] contains [q]. Intersect [s] with a sub-tree of [t]. *)
823

824
          inter s (if (p land n) = 0 then t0 else t1)
825

826
        else
827

828
          (* The prefixes disagree. *)
829

830
          Empty
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 ->
844
          ()
845 846

      | Leaf x, _ ->
847 848
          if mem x t then
            raise NotDisjoint
849
      | _, Leaf x ->
850 851
          if mem x s then
            raise NotDisjoint
852 853

      | Branch(p, m, s0, s1), Branch(q, n, t0, t1) ->
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
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 ->
876
        ()
877
    | Leaf x ->
878
        f x
879
    | Branch (_, _, tree0, tree1) ->
880 881
        iter f tree0;
        iter f tree1
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
891 892 893 894 895 896
    |   Empty ->
        accu
    |   Leaf x ->
        f x accu
    |   Branch (_, _, s0, s1) ->
        fold f s1 (fold f s0 accu)
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
      | [] ->
917
          None
918
      | Empty :: parent ->
919 920
          remainder := parent;
          next()
921
      | (Leaf x) :: parent ->
922 923
          remainder := parent;
          Some x
924
      | (Branch(_, _, s0, s1)) :: parent ->
925 926
          remainder := s0 :: s1 :: parent;
          next () in
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 ->
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)
945 946 947
      ) s1;
      match iterator2() with
      | None ->
948
          0
949
      | Some _ ->
950
          -1
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, _ ->
970
          ()
971 972 973
      | _, Empty

      | Branch _, Leaf _ ->
974
          raise NotSubset
975
      | Leaf x, _ ->
976 977
          if not (mem x t) then
            raise NotSubset
978 979 980

      | Branch(p, m, s0, s1), Branch(q, n, t0, t1) ->

981
          if (p = q) && (m = n) then begin
982

983 984
            diff s0 t0;
            diff s1 t1
985

986 987
          end
          else if (X.shorter n m) && (match_prefix p q n) then
988

989
            diff s (if (p land n) = 0 then t0 else t1)
990

991
          else
992

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. *)
995

996
            raise NotSubset in
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. *)

1011
  (* [domain m] returns [m]'s domain. *)
1012 1013 1014

  let rec domain = function
    | Empty ->
1015
        Domain.Empty
1016
    | Leaf (k, _) ->
1017
        Domain.Leaf k
1018
    | Branch (p, m, t0, t1) ->
1019
        Domain.Branch (p, m, domain t0, domain t1)
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 ->
1025
        Empty
1026
    | Domain.Leaf k ->
1027
        Leaf (k, f k)
1028
    | Domain.Branch (p, m, t0, t1) ->
1029
        Branch(p, m, lift f t0, lift f t1)
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 ->
1037
        Empty
1038
    | Empty, _ ->
1039
        t1
1040
    | _, Empty ->
1041
        t0
1042
    | _, _ ->
1043
        Branch(p, m, t0, t1)
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

1052 1053 1054
      | Empty, _
      | _, Domain.Empty ->
          s
1055

1056 1057 1058 1059
      | Leaf (k, _), _ ->
          if Domain.mem k t then Empty else s
      | _, Domain.Leaf k ->
          remove k s
1060

1061
      | Branch(p, m, s0, s1), Domain.Branch(q, n, t0, t1) ->
1062
          if (p = q) && (m = n) then
1063

1064
            build p m (corestrict s0 t0) (corestrict s1 t1)
1065

1066
          else if (X.shorter m n) && (match_prefix q p m) then
1067

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)
1072

1073
          else if (X.shorter n m) && (match_prefix p q n) then
1074

1075
            corestrict s (if (p land n) = 0 then t0 else t1)
1076

1077
          else
1078

1079
            s
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)