123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346(*
* Ptset: Sets of integers implemented as Patricia trees.
* Copyright (C) 2000 Jean-Christophe FILLIATRE
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License version 2, as published by the Free Software Foundation.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU Library General Public License version 2 for more details
* (enclosed in the file LGPL).
*)(*i ptset.ml 1.8 2001/06/28 07:05:55 filliatr Exp i*)(*s Sets of integers implemented as Patricia trees, following Chris
Okasaki and Andrew Gill's paper {\em Fast Mergeable Integer Maps}
({\tt\small http://www.cs.columbia.edu/\~{}cdo/papers.html\#ml98maps}).
Patricia trees provide faster operations than standard library's
module [Set], and especially very fast [union], [subset], [inter]
and [diff] operations. *)(*s The idea behind Patricia trees is to build a {\em trie} on the
binary digits of the elements, and to compact the representation
by branching only one the relevant bits (i.e. the ones for which
there is at least on element in each subtree). We implement here
{\em little-endian} Patricia trees: bits are processed from
least-significant to most-significant. The trie is implemented by
the following type [t]. [Empty] stands for the empty trie, and
[Leaf k] for the singleton [k]. (Note that [k] is the actual
element.) [Branch (m,p,l,r)] represents a branching, where [p] is
the prefix (from the root of the trie) and [m] is the branching
bit (a power of 2). [l] and [r] contain the subsets for which the
branching bit is respectively 0 and 1. Invariant: the trees [l]
and [r] are not empty. *)(*i*)typeelt=int(*i*)typet=|Empty|Leafofint|Branchofint*int*t*t(*s Example: the representation of the set $\{1,4,5\}$ is
$$\mathtt{Branch~(0,~1,~Leaf~4,~Branch~(1,~4,~Leaf~1,~Leaf~5))}$$
The first branching bit is the bit 0 (and the corresponding prefix
is [0b0], not of use here), with $\{4\}$ on the left and $\{1,5\}$ on the
right. Then the right subtree branches on bit 2 (and so has a branching
value of $2^2 = 4$), with prefix [0b01 = 1]. *)(*s Empty set and singletons. *)letempty=Emptyletis_empty=functionEmpty->true|_->falseletsingletonk=Leafk(*s Testing the occurrence of a value is similar to the search in a
binary search tree, where the branching bit is used to select the
appropriate subtree. *)letzero_bitkm=(klandm)==0letrecmemk=function|Empty->false|Leafj->k==j|Branch(_,m,l,r)->memk(ifzero_bitkmthenlelser)(*s The following operation [join] will be used in both insertion and
union. Given two non-empty trees [t0] and [t1] with longest common
prefixes [p0] and [p1] respectively, which are supposed to
disagree, it creates the union of [t0] and [t1]. For this, it
computes the first bit [m] where [p0] and [p1] disagree and create
a branching node on that bit. Depending on the value of that bit
in [p0], [t0] will be the left subtree and [t1] the right one, or
the converse. Computing the first branching bit of [p0] and [p1]
uses a nice property of twos-complement representation of integers. *)letlowest_bitx=xland(-x)letbranching_bitp0p1=lowest_bit(p0lxorp1)letmaskpm=pland(m-1)letjoin(p0,t0,p1,t1)=letm=branching_bitp0p1inifzero_bitp0mthenBranch(maskp0m,m,t0,t1)elseBranch(maskp0m,m,t1,t0)(*s Then the insertion of value [k] in set [t] is easily implemented
using [join]. Insertion in a singleton is just the identity or a
call to [join], depending on the value of [k]. When inserting in
a branching tree, we first check if the value to insert [k]
matches the prefix [p]: if not, [join] will take care of creating
the above branching; if so, we just insert [k] in the appropriate
subtree, depending of the branching bit. *)letmatch_prefixkpm=(maskkm)==pletaddkt=letrecins=function|Empty->Leafk|Leafjast->ifj==kthentelsejoin(k,Leafk,j,t)|Branch(p,m,t0,t1)ast->ifmatch_prefixkpmthenifzero_bitkmthenBranch(p,m,inst0,t1)elseBranch(p,m,t0,inst1)elsejoin(k,Leafk,p,t)ininst(*s The code to remove an element is basically similar to the code of
insertion. But since we have to maintain the invariant that both
subtrees of a [Branch] node are non-empty, we use here the
``smart constructor'' [branch] instead of [Branch]. *)letbranch=function|(_,_,Empty,t)->t|(_,_,t,Empty)->t|(p,m,t0,t1)->Branch(p,m,t0,t1)letremovekt=letrecrmv=function|Empty->Empty|Leafjast->ifk==jthenEmptyelset|Branch(p,m,t0,t1)ast->ifmatch_prefixkpmthenifzero_bitkmthenbranch(p,m,rmvt0,t1)elsebranch(p,m,t0,rmvt1)elsetinrmvt(*s One nice property of Patricia trees is to support a fast union
operation (and also fast subset, difference and intersection
operations). When merging two branching trees we examine the
following four cases: (1) the trees have exactly the same
prefix; (2/3) one prefix contains the other one; and (4) the
prefixes disagree. In cases (1), (2) and (3) the recursion is
immediate; in case (4) the function [join] creates the appropriate
branching. *)letrecmerge=function|Empty,t->t|t,Empty->t|Leafk,t->addkt|t,Leafk->addkt|(Branch(p,m,s0,s1)ass),(Branch(q,n,t0,t1)ast)->ifm==n&&match_prefixqpmthen(* The trees have the same prefix. Merge the subtrees. *)Branch(p,m,merge(s0,t0),merge(s1,t1))elseifm<n&&match_prefixqpmthen(* [q] contains [p]. Merge [t] with a subtree of [s]. *)ifzero_bitqmthenBranch(p,m,merge(s0,t),s1)elseBranch(p,m,s0,merge(s1,t))elseifm>n&&match_prefixpqnthen(* [p] contains [q]. Merge [s] with a subtree of [t]. *)ifzero_bitpnthenBranch(q,n,merge(s,t0),t1)elseBranch(q,n,t0,merge(s,t1))else(* The prefixes disagree. *)join(p,s,q,t)letunionst=merge(s,t)(*s When checking if [s1] is a subset of [s2] only two of the above
four cases are relevant: when the prefixes are the same and when the
prefix of [s1] contains the one of [s2], and then the recursion is
obvious. In the other two cases, the result is [false]. *)letrecsubsets1s2=match(s1,s2)with|Empty,_->true|_,Empty->false|Leafk1,_->memk1s2|Branch_,Leaf_->false|Branch(p1,m1,l1,r1),Branch(p2,m2,l2,r2)->ifm1==m2&&p1==p2thensubsetl1l2&&subsetr1r2elseifm1>m2&&match_prefixp1p2m2thenifzero_bitp1m2thensubsetl1l2&&subsetr1l2elsesubsetl1r2&&subsetr1r2elsefalse(*s To compute the intersection and the difference of two sets, we
still examine the same four cases as in [merge]. The recursion is
then obvious. *)letrecinters1s2=match(s1,s2)with|Empty,_->Empty|_,Empty->Empty|Leafk1,_->ifmemk1s2thens1elseEmpty|_,Leafk2->ifmemk2s1thens2elseEmpty|Branch(p1,m1,l1,r1),Branch(p2,m2,l2,r2)->ifm1==m2&&p1==p2thenmerge(interl1l2,interr1r2)elseifm1<m2&&match_prefixp2p1m1theninter(ifzero_bitp2m1thenl1elser1)s2elseifm1>m2&&match_prefixp1p2m2theninters1(ifzero_bitp1m2thenl2elser2)elseEmptyletrecdiffs1s2=match(s1,s2)with|Empty,_->Empty|_,Empty->s1|Leafk1,_->ifmemk1s2thenEmptyelses1|_,Leafk2->removek2s1|Branch(p1,m1,l1,r1),Branch(p2,m2,l2,r2)->ifm1==m2&&p1==p2thenmerge(diffl1l2,diffr1r2)elseifm1<m2&&match_prefixp2p1m1thenifzero_bitp2m1thenmerge(diffl1s2,r1)elsemerge(l1,diffr1s2)elseifm1>m2&&match_prefixp1p2m2thenifzero_bitp1m2thendiffs1l2elsediffs1r2elses1(*s All the following operations ([cardinal], [iter], [fold], [for_all],
[exists], [filter], [partition], [choose], [elements]) are
implemented as for any other kind of binary trees. *)letreccardinal=function|Empty->0|Leaf_->1|Branch(_,_,t0,t1)->cardinalt0+cardinalt1letreciterf=function|Empty->()|Leafk->fk|Branch(_,_,t0,t1)->iterft0;iterft1letrecfoldfsaccu=matchswith|Empty->accu|Leafk->fkaccu|Branch(_,_,t0,t1)->foldft0(foldft1accu)letrecfor_allp=function|Empty->true|Leafk->pk|Branch(_,_,t0,t1)->for_allpt0&&for_allpt1letrecexistsp=function|Empty->false|Leafk->pk|Branch(_,_,t0,t1)->existspt0||existspt1letfilterps=letrecfiltacc=function|Empty->acc|Leafk->ifpkthenaddkaccelseacc|Branch(_,_,t0,t1)->filt(filtacct0)t1infiltEmptysletpartitionps=letrecpart(t,fasacc)=function|Empty->acc|Leafk->ifpkthen(addkt,f)else(t,addkf)|Branch(_,_,t0,t1)->part(partacct0)t1inpart(Empty,Empty)sletrecchoose=function|Empty->raiseNot_found|Leafk->k|Branch(_,_,t0,_)->chooset0(* we know that [t0] is non-empty *)letelementss=letrecelements_auxacc=function|Empty->acc|Leafk->k::acc|Branch(_,_,l,r)->elements_aux(elements_auxaccl)rinelements_aux[]s(*s There is no way to give an efficient implementation of [min_elt]
and [max_elt], as with binary search trees. The following
implementation is a traversal of all elements, barely more
efficient than [fold min t (choose t)] (resp. [fold max t (choose
t)]). Note that we use the fact that there is no constructor
[Empty] under [Branch] and therefore always a minimal
(resp. maximal) element there. *)letrecmin_elt=function|Empty->raiseNot_found|Leafk->k|Branch(_,_,s,t)->min(min_elts)(min_eltt)letrecmax_elt=function|Empty->raiseNot_found|Leafk->k|Branch(_,_,s,t)->max(max_elts)(max_eltt)(*s Another nice property of Patricia trees is to be independent of the
order of insertion. As a consequence, two Patricia trees have the
same elements if and only if they are structurally equal. *)letequal=(=)letcompare=compare(*i*)letmakel=List.fold_rightaddlempty(*i*)(*s Additional functions w.r.t to [Set.S]. *)letrecintersects1s2=match(s1,s2)with|Empty,_->false|_,Empty->false|Leafk1,_->memk1s2|_,Leafk2->memk2s1|Branch(p1,m1,l1,r1),Branch(p2,m2,l2,r2)->ifm1==m2&&p1==p2thenintersectl1l2||intersectr1r2elseifm1<m2&&match_prefixp2p1m1thenintersect(ifzero_bitp2m1thenl1elser1)s2elseifm1>m2&&match_prefixp1p2m2thenintersects1(ifzero_bitp1m2thenl2elser2)elsefalse