1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336(*
* Vect - Extensible arrays based on ropes
* Copyright (C) 2007 Mauricio Fernandez <mfp@acm.org>
* 2009 David Rajchenbach-Teller, LIFO, Universite d'Orleans
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version,
* with the special exception on linking described in file LICENSE.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*)moduleSTRING:sig(* this module must provide the following functions: *)type'at='aarrayvallength:'at->intvalmake:int->'a->'atvalcopy:'at->'atvalunsafe_get:'at->int->'avalunsafe_set:'at->int->'a->unitvalsub:'at->int->int->'atvaliter:('a->unit)->'at->unitval fold_right:('a->'b->'b)->'at->'b->'bvalappend:'at->'at->'atval concat:'atlist->'atend=BatArraytype'at=|Empty|Concatof'at*int*'at*int*int|Leafof'aSTRING.t(* these invariants may be incomplete, feel free to improve it *)letinvariantst=letrecinv_height =function|Empty|Leaf_->0|Concat(l,_,r,_,h)->assert(h=1+max(inv_heightl)(inv_heightr));hinletrecinv_length=function|Empty ->0|Leafa->STRING.lengtha|Concat(l,cl,r,cr,_)->assert(inv_lengthl=cl);assert(inv_lengthr=cr);cl+crinletrecother_invdepth=function|Empty ->assert(depth=0)|Leafa->assert(STRING.lengtha>0)|Concat(l,_,r,_,_)->other_inv(depth+1)l;other_inv(depth+1)rinignore (inv_heightt);ignore (inv_length t);other_inv 0ttype'aforest_element ={mutablec:'at;mutablelen:int}letstr_append=STRING.appendletstring_of_string_list=STRING.concatletsingletonx=Leaf[|x|](* 48limits maxrope size to 236.10^9 elements on 64 bit,
* ~ 734.10^6 on 32bit (length fields overflow after that) *)letmax_height=48(* actual size will be that plus 1 word header;
* the code assumes it's an even num.
* 32 gives up to 50% overhead in the worst case (all leaf nodes near
* half-filled; 8 words for bookkeeping, 16 words worth of data per leaf node *)letleaf_size=16exceptionOut_of_boundsletempty=Empty(* by construction, there cannot be Empty or Leaf "" leaves *)letis_empty=function|Empty->true|Leaf_|Concat_->falseletheight=function|Empty|Leaf_->0|Concat(_,_,_,_,h)->hletlength=function|Empty->0|Leafs->STRING.lengths|Concat(_,cl,_,cr,_)->cl+crletmake_concatlr=lethl=heightlandhr=heightrinletcl=lengthlandcr=lengthrinConcat(l,cl,r,cr,ifhl>=hrthenhl+1elsehr+1)letmin_len=letfib_tbl=Array.makemax_height0inlet recfibn=matchfib_tbl.(n)with|0->letlast=fib(n-1)andprev=fib(n-2)inletr=last+previnletr=ifr>lastthenrelselastin(* check overflow *)fib_tbl.(n)<-r;r|n->ninfib_tbl.(0)<-leaf_size+1;fib_tbl.(1)<-3*leaf_size/2+1;Array.initmax_height(funi->ifi=0then1elsefib(i-1))letmax_length=min_len.(Array.length min_len-1)letconcat_fastlr=matchlwith|Empty->r|Leaf_|Concat_->matchrwith|Empty->l|Leaf_|Concat_->make_concatlr(* based on Hans-J. Boehm's *)letadd_forestforestropelen=leti=ref0inletsum=refemptyinwhilelen>min_len.(!i+1)doifforest.(!i).c<>Emptythenbeginsum:=concat_fastforest.(!i).c!sum;forest.(!i).c<-Emptyend;incridone;sum:=concat_fast !sumrope;letsum_len=ref(length!sum)inwhile !sum_len>=min_len.(!i)doifforest.(!i).c<>Emptythenbeginsum:=concat_fastforest.(!i).c!sum;sum_len :=!sum_len +forest.(!i).len;forest.(!i).c<-Empty;end;incridone;decri;forest.(!i).c<-!sum;forest.(!i).len<-!sum_lenletconcat_forestforest=Array.fold_left (funsx->concat_fast x.cs)Emptyforestletrecbalance_insertropelenforest=matchropewith|Empty->()|Leaf_->add_forestforestropelen|Concat(l,cl,r,cr,h)whenh>=max_height||len<min_len.(h)->balance_insertlclforest;balance_insertrcrforest|Concat_asx->add_forestforestxlen(* function orbalanced *)letbalancer=matchrwith|Empty->Empty|Leaf_->r|Concat_->letforest=Array.initmax_height(fun_->{c=Empty;len=0})inbalance_insertr(lengthr)forest;concat_forestforestletbal_if_neededlr=letr=make_concat lrinifheightr<max_heightthenrelsebalancerletconcat_strl=function|Empty|Concat_->assertfalse|Leafrsasr->letlenr=STRING.lengthrsinmatchlwith|Empty->r|Leafls->letslen=lenr+STRING.lengthlsinifslen<=leaf_sizethenLeaf(str_appendlsrs)elsemake_concatlr(* height = 1 *)|Concat(ll,cll,Leaflrs,clr,h)->let slen=clr+lenrinifclr+lenr <=leaf_sizethenConcat(ll,cll,Leaf(str_appendlrs rs),slen,h)elsebal_if_neededlr|Concat_->bal_if_neededlrletappend_charcr=concat_strr(Leaf(STRING.make1c))letconcatl=function|Empty->l|Leaf_asr->concat_strlr|Concat(Leafrls,rlc,rr,rc,h)asr->(matchlwith|Empty->r|Concat_->bal_if_neededlr|Leafls->letslen=rlc+STRING.lengthlsinifslen<= leaf_sizethenConcat(Leaf(str_appendlsrls),slen,rr,rc,h)elsebal_if_neededlr)|Concat_asr->(matchlwith|Empty->r|Leaf_|Concat_->bal_if_neededlr)letprepend_charcr=concat(Leaf(STRING.make1c))rletrecgetti=matchtwith|Empty->raiseOut_of_bounds|Leaf s->ifi>=0&&i<STRING.lengthsthenSTRING.unsafe_getsielseraiseOut_of_bounds|Concat (l,cl,r,_cr,_)->if i<clthengetlielsegetr(i-cl)letrecsettix=matchtwith|Empty->raiseOut_of_bounds|Leaf s->ifi>=0&&i<STRING.lengthsthen(lets=STRING.copysinSTRING.unsafe_setsix;Leafs)elseraiseOut_of_bounds|Concat (l,cl,r,_cr,_)->if i<clthenconcat(setlix)relseconcatl(setr(i-cl)x)letat=getletrecmodifytif=matchtwith|Empty->raiseOut_of_bounds|Leaf s->ifi>=0&&i<STRING.lengthsthen(lets=STRING.copysinSTRING.unsafe_setsi(f(STRING.unsafe_getsi));Leafs)elseraiseOut_of_bounds|Concat (l,cl,r,_cr,_)->if i<clthenconcat(modifylif)relseconcatl(modifyr(i-cl)f)letof_string=function|[||]->Empty|s->letreclooprsleni=ifi<lenthen(* len -i> 0, thus Leaf "" can't happen *)loop(concatr(Leaf(STRING.subsi(BatInt.min(len-i)leaf_size))))slen(i+leaf_size)elserinloopEmptys(STRING.lengths)0letrecmakelenc=letrecconcatlooplenir=ifi<=lenthenconcatlooplen(i*2)(concatrr)elseriniflen=0thenEmptyelseiflen<=leaf_sizethenLeaf (STRING.makelenc)elseletrope=concatlooplen2(of_string(STRING.make1c))inconcatrope(make(len-lengthrope)c)(*overridden argument order below *)letrecsubstartlen=function|Empty->ifstart<>0||len<>0thenraise Out_of_boundselseEmpty|Leafs->iflen>0then(* Leaf "" cannot happen *)(tryLeaf(STRING.subsstartlen)with_->raiseOut_of_bounds)else iflen<0||start<0||start>STRING.lengthsthenraiseOut_of_boundselse Empty|Concat(l,cl,r,cr,_)->ifstart<0||len<0||start +len >cl+crthenraiseOut_of_bounds;let left=ifstart=0theniflen>=clthenlelsesub0lenlelseifstart>clthenEmptyelseifstart+len>=clthensub start(cl-start)lelsesubstartlenlinletright=ifstart<=clthenlet upto=start+leninifupto=cl+crthenrelseifupto<clthenEmptyelse sub0(upto-cl)relsesub(start -cl)lenrinconcatleftright(* change argument order on Vect.sub *)letsubvsl=subslvletinsertstartroper=concat (concat(subr0start)rope)(subrstart(lengthr-start))(*$T insert(of_list [0;1;2;3] |> insert 0 (singleton 10) |> to_list) = [10;0;1;2;3]
(of_list [0;1;2;3] |> insert 1 (singleton 10) |> to_list) = [0;10;1;2;3]
(of_list [0;1;2;3] |> insert 2 (singleton 10) |> to_list) = [0;1;10;2;3]
(of_list [0;1;2;3] |> insert 3 (singleton 10) |> to_list) = [0;1;2;10;3]
(of_list [0;1;2;3] |> insert 4 (singleton 10) |> to_list) = [0;1;2;3;10]
try of_list [0;1;2;3] |> insert (-1) (singleton 10) |> to_list |> ignore; false; with _ -> true
try of_list [0;1;2;3] |> insert 5 (singleton 10) |> to_list |> ignore; false; with _ -> true
(of_list [] |> insert 0 (singleton 1) |> to_list) = [1]
(of_list [0] |> insert 0 (singleton 1) |> to_list) = [1; 0]
(of_list [0] |> insert 1 (singleton 1) |> to_list) = [0; 1]
*)letremovestartlenr=concat (subr0start)(subr(start+len)(lengthr-start -len))(*$Qremove(Q.pair (Q.pair Q.small_int Q.small_int) (Q.small_int)) \
(fun ((n1, n2), lr) -> \
let init len = of_list (BatList.init len (fun i -> i)) in \
let n, lu = min n1 n2, max n1 n2 in \
let u, r = init lu, init lr in \
equal (=) u (u |> insert n r |> remove n (length r)))
*)letto_stringr=letrecstringsl=function|Empty ->l|Leafs->s::l|Concat(left,_,right,_,_)->strings(stringslright)leftinstring_of_string_list (strings[]r)letreciterf=function|Empty->()|Leafs->STRING.iterfs|Concat(l,_,r,_,_)->iterfl;iterfrtype'aiter=E|Cof'aSTRING.t*int*'at*'aiterlet reccons_iterst=matchswith|Empty->t|Leafs->C(s,0,Empty,t)|Concat(l,_llen,r,_rlen,_h)->cons_iter l(cons_iterrt)letrecrev_cons_iterst=matchswith|Empty->t|Leafs->C(s,(STRING.lengths-1),Empty,t)|Concat(l,_,r,_,_)->rev_cons_iterr(rev_cons_iterlt)letenum_nextl()=match!lwith|E->raiseBatEnum.No_more_elements|C(s,p,r,t)->ifp+1=STRING.lengthsthenl:=cons_iterrtelsel:=C(s,p+1,r,t);STRING.unsafe_getspletenum_backwards_nextl()=match!lwith|E->raiseBatEnum.No_more_elements|C(s,p,r,t)->ifp=0thenl:=rev_cons_iterrtelsel:=C(s,p-1,r,t);STRING.unsafe_getspletenum_countl()=letrecauxn=function|E->n|C(s,p,m,t)->aux(n+(STRING.lengths-p)+lengthm)tinaux0!lletrev_enum_countl()=letrecauxn=function|E->n|C(_s,p,m,t)->aux(n+(p+1)+lengthm)tinaux0!lletenumt=letrecmakel=letl=reflinletclone()=make!linBatEnum.make~next:(enum_nextl)~count:(enum_countl)~cloneinmake(cons_itertE)letbackwardst=letrecmakel=letl=reflinletclone()=make!linBatEnum.make~next:(enum_backwards_nextl)~count:(rev_enum_countl)~cloneinmake(rev_cons_itertE)letof_enume=BatEnum.fold(funaccx->append_char xacc)emptyeletof_backwardse=BatEnum.fold(funaccx->prepend_charxacc)emptyeletiterifr=letrecauxfi=function|Empty->()|Leafs->forj=0toSTRING.lengths-1dof(i+j)(STRING.unsafe_getsj)done|Concat(l,cl,r,_,_)->auxfil;auxf(i+cl)rinauxf0rletrecrangeiterfstartlen=function|Empty->ifstart<>0||len<>0thenraise Out_of_bounds|Leaf s->letn=start+leninletlens=STRING.lengthsinifstart>=0&&len>=0&&n<= lensthenfori=start ton-1dof(STRING.unsafe_getsi)doneelseraiseOut_of_bounds|Concat (l,cl,r,cr,_)->ifstart<0||len<0||start +len >cl+crthenraiseOut_of_bounds;if start<clthenbeginletupto=start+leninifupto<=clthenrangeiter fstartlenlelsebeginrangeiterfstart(cl-start)l;rangeiterf0(upto-cl)rendendelsebeginrangeiterf(start-cl)lenrendletrecfoldfa=function|Empty->a|Leafs->letacc=refainfori=0toSTRING.lengths-1doacc:=f!acc(STRING.unsafe_get si)done;!acc|Concat(l,_,r,_,_)->foldf(foldfal)rletfoldifav=letrecauxia=function|Empty->a|Leafs->letacc=refainforj=0toSTRING.lengths-1doacc:=f(i+j)!acc(STRING.unsafe_getsj)done;!acc|Concat(l,cl,r,_,_)->aux(i+cl)(auxial)rinaux0avletfold_left=foldletfold_right (f:'a->'b->'b)(v:'at)(acc:'b):'b=letrec aux(acc:'b)=function|Empty->acc|Leafs->STRING.fold_rightfsacc|Concat(l,_,r,_,_)->aux(auxaccr)linauxaccvletreducefv=letacc=ref(getv0)inrangeiter(fune->acc:=f!acce)1(lengthv-1)v;!accletof_array=of_stringletto_array =to_stringletappend =append_charletprepend =prepend_charletrecmapf=function|Empty->Empty|Leafa->Leaf(BatArray.mapfa)|Concat(l,cl,r,cr,h)->letl=mapflinletr=mapfrinConcat(l,cl,r,cr,h)letmapifv=letoff=ref0inmap(fun x->f(BatRef.post_incroff)x)vletrecexists f=function|Empty->false|Leafa->BatArray.existsfa|Concat(l,_,r,_,_)->existsfl||existsfr(*$Texists
exists (fun x -> x = 2) empty = false
exists (fun x -> x = 2) (singleton 2) = true
exists (fun x -> x = 2) (singleton 3) = false
exists (fun x -> x = 2) (of_array [|1; 3|]) = false
exists (fun x -> x = 2) (of_array [|2; 3|]) = true
exists (fun x -> x = 2) (concat (singleton 1) (singleton 3)) = false
exists (fun x -> x = 2) (concat (singleton 1) (of_array [|2|])) = true
exists (fun x -> x = 2) (concat (singleton 2) (singleton 3)) = true
*)(*$Q exists
(Q.list Q.small_int) (fun li -> let p i = (i mod 4 = 0) in List.exists p li = exists p (of_list li))
*)letrecfor_allf=function|Empty->true|Leafa->BatArray.for_allfa|Concat(l,_,r,_,_)->for_allfl&&for_allfr(*$Tfor_all
for_all (fun x -> x = 2) empty = true
for_all (fun x -> x = 2) (singleton 2) = true
for_all (fun x -> x = 2) (singleton 3) = false
for_all (fun x -> x = 2) (of_array [|2; 3|]) = false
for_all (fun x -> x = 2) (of_array [|2; 2|]) = true
for_all (fun x -> x = 2) (concat (singleton 1) (singleton 2)) = false
for_all (fun x -> x = 2) (concat (singleton 2) (of_array [|2|])) = true
for_all (fun x -> x = 2) (concat (singleton 2) (singleton 3)) = false
*)(*$Q for_all
(Q.list Q.small_int) (fun li -> let p i = (i mod 4 > 0) in List.for_all p li = for_all p (of_list li))
*)letrecfind_optf=function|Empty->None|Leafa->BatArray.Exceptionless.findfa|Concat(l,_,r,_,_)->beginmatchfind_optflwith|Some_asresult->result|None ->find_optfrend(*$T find_opt
[0;1;2;3] |> of_list |> find_opt ((=) 2) = Some 2
[0;1;2;3] |> of_list |> find_opt ((=) 4) = None
[] |> of_list |> find_opt ((=) 2) = None
concat (of_list [0; 1]) (of_list ([2; 3])) |> find_opt (fun n -> n > 0) = Some 1
*)letfindfv=matchfind_optfvwith|None->raiseNot_found|Somex->x(*$T find
[0;1;2;3] |> of_list |> find ((=) 2) = 2
try [0;1;2;3] |> of_list |> find ((=) 4) |> ignore; false with Not_found -> true
try [] |> of_list |> find ((=) 2) |> ignore; false with Not_found -> true
concat (of_list [0; 1]) (of_list ([2; 3])) |> find (fun n -> n > 0) = 1
*)letfindifv=letoff=ref(-1)inignore(find (funx->letresult=fxinincroff;result)v);!offletpartitionpv=fold_left(fun(yes,no)x->ifpxthen(append xyes,no)else(yes,appendxno))(empty,empty)vletfind_allpv=fold_left(funaccx->ifpxthenappendxaccelseacc)emptyvlet memmv=trylet_=find((=)m)vintruewithNot_found->falseletmemqmv=trylet_=find((==)m)vintruewithNot_found ->falseletfirstv=getv0letlastv=getv(lengthv-1)letshiftv=firstv,subv1(lengthv-1)letpopv=lastv,subv0(lengthv-1)letto_listr=letrecauxacc=function|Empty->acc|Leafa->Array.fold_right(funxl->x::l)aacc|Concat(l,_,r,_,_)->aux(auxaccr)linaux[]rletfilter=find_allletfilter_mapf=fold(funaccx->matchfxwith|None->acc|Somev->appendvacc)Emptyletdestructive_setvix=letrecauxi=function|Empty ->raiseOut_of_bounds|Leafs->ifi>=0&&i<STRING.lengthsthenSTRING.unsafe_setsixelseraiseOut_of_bounds|Concat(l,cl,r,_cr,_)->ifi<clthenauxilelse aux(i-cl)rinauxivletof_listl=of_array(Array.of_listl)letinitnf=ifn<0||n>max_lengththeninvalid_arg"Vect.init";(* Create as many arrays as we need to store all the data *)letrecauxoffacc=ifoff>=nthen accelseletlen=minleaf_size(n-off)inletarr=Array.initlen(fun i->f(off+i))inaux(off+len)(arr::acc)inletbase=aux0[]in(* And then concatenate them *)List.fold_left(fun(acc:'at)(array:'aarray)->concat(of_arrayarray)acc)(empty:'at)(base:'aarraylist)(*$T init
init 1000 (fun x -> x * x) |> to_array = Array.init 1000 (fun x -> x * x)
*)letprint?(first="[|")?(last="|]")?(sep="; ")print_aoutt=BatEnum.print ~first~last~sepprint_a out(enumt)letcompare cmp_valv1v2=BatEnum.comparecmp_val(enumv1)(enumv2)letequaleq_valv1v2=BatEnum.equaleq_val (enumv1)(enum v2)letordord_val v1v2=letcmp_val=BatOrd.compord_val inBatOrd.ord0(BatEnum.comparecmp_val (enumv1)(enum v2))moduleLabels=structletinitn~f=initnfletgetv~n=getvnletatv~n=atvnletsetv~n~elem=setvnelemletmodifyv~n~f=modifyvnfletsubv~m~n=subvmnletinsert~n~sub=insertnsubletremove~m~n=removemnletiter~f=iterfletiteri~f=iterifletmap~f=mapfletmapi~f=mapifletfor_all~f=for_allfletexists~f=existsfletfind~f=findfletmem~elem=memelemlet memq~elem=memqelemlet findi~f=findifletfilter~f=filterfletfilter_map~f=filter_mapfletfind_all~f=find_allfletpartition~f=partitionfletdestructive_setv~n~elem=destructive_set vnelemletrangeiter~f~m~n=rangeiterfmnletfold_left~f~init=fold_leftfinitletfold~f~init=foldfinitletreduce~f=reducefletfold_right~fv~init=fold_rightfvinitletfoldi~f~init=foldifinitend(* Functorial interface *)moduletypeRANDOMACCESS=sigtype'atvalempty:'atvalget:'at->int->'avalunsafe_get:'at->int->'avalset:'at->int->'a->unitvalunsafe_set:'at->int->'a->unitvalappend:'at->'at->'atval concat:'atlist->'atvallength:'at->intvalcopy:'at->'atvalsub:'at->int->int->'atvalmake:int->'a->'atvaliter:('a->unit)->'at->unitval map:('a->'b)->'at->'btvalfold_right:('a->'b->'b)->'at->'b->'bvalenum:'at->'aBatEnum.tval backwards:'at->'aBatEnum.tval of_enum:'aBatEnum.t->'atvalof_backwards :'aBatEnum.t->'atendmoduleMake(RANDOMACCESS :RANDOMACCESS)(PARAM:sigvalmax_height:intvalleaf_size:intend)=structmoduleSTRING=RANDOMACCESS(*$inject module Test_functor = struct
module STRING = struct
include BatArray
let empty = [||]
end
module PARAM = struct let max_height = 256 let leaf_size = 256 end
module Instance = Make(STRING)(PARAM)
open Instance
*)type'at=|Empty|Concatof'at*int*'at*int*int|Leaf of'aSTRING.tletmax_height=PARAM.max_heightletleaf_size=PARAM.leaf_sizeletmin_len=letfib_tbl=Array.makemax_height0inletrecfibn=matchfib_tbl.(n)with|0->letlast=fib(n-1)andprev=fib(n-2)inletr=last+previnletr=if r>lastthenrelselastin(* check overflow *)fib_tbl.(n)<-r;r|n->ninfib_tbl.(0)<-leaf_size+1;fib_tbl.(1)<-3*leaf_size/2+1;Array.initmax_height(funi->ifi=0then1elsefib(i-1))letmax_length=min_len.(Array.length min_len-1)letinvariantst=letrecinv_height=function|Empty|Leaf_->0|Concat(l,_,r,_,h)->assert(h=1+max(inv_heightl)(inv_heightr));hinletrecinv_length=function|Empty ->0|Leafa->STRING.lengtha|Concat(l,cl,r,cr,_)->assert(inv_lengthl=cl);assert(inv_lengthr=cr);cl+crinletrecother_invdepth=function|Empty ->assert(depth=0)|Leafa->assert(STRING.lengtha>0)|Concat(l,_,r,_,_)->other_inv(depth+1)l;other_inv (depth+1)rinignore(inv_heightt);assert(inv_lengtht<max_length);other_inv0ttype'aforest_element ={mutablec:'at;mutablelen:int}letstr_append=STRING.appendletstring_of_string_list=STRING.concatlet singletonx=Leaf(STRING.make1x)exceptionOut_of_boundsletempty=Empty(* by construction, there cannot be Empty or Leaf "" leaves *)letis_empty=function|Empty ->true|Leaf_|Concat_->falseletheight=function|Empty |Leaf_->0|Concat(_,_,_,_,h)->hletlength=function|Empty ->0|Leafs->STRING.lengths|Concat(_,cl,_,cr,_)->cl+crletmake_concatlr=lethl=height landhr=heightrinletcl=lengthlandcr=lengthrinConcat(l,cl,r,cr,ifhl>=hrthenhl+1elsehr+1)letconcat_fastlr=matchlwith|Empty->r|Leaf_|Concat_->matchrwith|Empty->l|Leaf_|Concat_->make_concatlr(* based on Hans-J. Boehm's *)letadd_forestforestropelen=leti=ref0inletsum=ref emptyinwhile len >min_len.(!i+1)doifforest.(!i).c<>Emptythenbeginsum:=concat_fastforest.(!i).c!sum;forest.(!i).c<-Emptyend;incridone;sum:=concat_fast!sumrope;letsum_len=ref (length!sum)inwhile!sum_len>=min_len.(!i)doifforest.(!i).c<>Emptythenbeginsum:=concat_fastforest.(!i).c!sum;sum_len:=!sum_len+forest.(!i).len;forest.(!i).c<-Empty;end;incridone;decri;forest.(!i).c<-!sum;forest.(!i).len<-!sum_lenletconcat_forestforest=Array.fold_left (funsx->concat_fast x.cs)Emptyforestletrecbalance_insertropelenforest=matchropewith|Empty->()|Leaf_->add_forestforestropelen|Concat(l,cl,r,cr,h)whenh>=max_height||len<min_len.(h)->balance_insertlclforest;balance_insertrcrforest|Concat_asx->add_forestforestxlen(* function orbalanced *)letbalancer=matchrwith|Empty->Empty|Leaf_->r|Concat_->letforest=Array.initmax_height(fun_->{c=Empty;len=0})inbalance_insertr(lengthr)forest;concat_forestforestletbal_if_neededlr=letr=make_concat lrinifheightr<max_heightthenrelsebalancerletconcat_strl=function|Empty|Concat_->assertfalse|Leafrsasr->letlenr=STRING.lengthrsinmatchlwith|Empty->r|Leafls->letslen=lenr+STRING.lengthlsinifslen<= leaf_sizethenLeaf(str_appendlsrs)elsemake_concatlr(* height = 1 *)|Concat(ll,cll,Leaflrs,clr,h)->letslen=clr+lenrinifclr+lenr<=leaf_sizethenConcat(ll,cll,Leaf(str_appendlrs rs),slen,h)elsebal_if_neededlr|Concat_->bal_if_neededlrletappend_charcr=concat_strr(Leaf(STRING.make1c))letconcatl=function|Empty ->l|Leaf_asr->concat_strlr|Concat(Leafrls,rlc,rr,rc,h)asr->(matchlwith|Empty->r|Concat_->bal_if_neededlr|Leafls->letslen=rlc+STRING.lengthlsinifslen<=leaf_sizethenConcat(Leaf(str_appendlsrls),slen,rr,rc,h)elsebal_if_neededlr)|Concat_asr->(matchlwith|Empty->r|Leaf_|Concat_->bal_if_neededlr)letprepend_charcr=concat(Leaf(STRING.make1c))rletrecgetti=matchtwith|Empty->raiseOut_of_bounds|Leafs->ifi>=0&&i<STRING.lengthsthenSTRING.unsafe_getsielseraiseOut_of_bounds|Concat(l,cl,r,_cr,_)->ifi<clthengetlielse getr(i-cl)letrecsettix=matchtwith|Empty->raiseOut_of_bounds|Leafs->ifi>=0&&i<STRING.lengthsthen(lets=STRING.copysinSTRING.unsafe_setsix;Leafs)elseraiseOut_of_bounds|Concat(l,cl,r,_cr,_)->ifi<clthenconcat(setlix)relseconcatl(setr(i-cl)x)letat=getletrecmodifytif=matchtwith|Empty->raiseOut_of_bounds|Leafs->ifi>=0&&i<STRING.lengthsthen(lets=STRING.copysinSTRING.unsafe_setsi(f(STRING.unsafe_getsi));Leafs)elseraiseOut_of_bounds|Concat(l,cl,r,_cr,_)->ifi<clthenconcat(modifylif)relseconcatl(modifyr(i-cl)f)letof_strings=ifSTRING.length s=0thenEmptyelseletreclooprsleni=ifi<lenthen(* len -i> 0, thus Leaf "" can't happen *)loop(concatr(Leaf(STRING.subsi(BatInt.min(len-i)leaf_size))))slen(i+leaf_size)elserinloopEmptys(STRING.lengths)0letrecmakelenc=letrecconcatlooplenir=ifi<=lenthenconcatlooplen(i*2)(concatrr)elseriniflen=0thenEmptyelse iflen<=leaf_sizethenLeaf (STRING.makelenc)elseletrope=concatlooplen2(of_string(STRING.make1c))inconcatrope(make(len-lengthrope)c)(* overridden argument order below *)letrecsubstartlen=function|Empty->ifstart<>0||len<>0thenraise Out_of_boundselseEmpty|Leafs->iflen>0then(* Leaf "" cannot happen *)(tryLeaf(STRING.subsstartlen)with_->raiseOut_of_bounds)elseiflen<0||start<0||start>STRING.lengthsthenraiseOut_of_boundselseEmpty|Concat(l,cl,r,cr,_)->ifstart<0||len<0||start +len >cl+crthenraiseOut_of_bounds;letleft=ifstart=0theniflen>=clthenlelsesub0lenlelseifstart >clthenEmptyelse ifstart+len>=clthensubstart (cl-start)lelsesubstartlenlinletright=ifstart<=clthenletupto =start+leninifupto=cl+crthenrelseifupto<clthenEmptyelsesub0(upto-cl)relsesub(start-cl)lenrinconcatleftright(* change argument order on Vect.sub *)letsubvsl=subslvletinsertstartroper=concat (concat(subr0start)rope)(subrstart(lengthr-start))letremovestart lenr=concat (subr0start)(subr(start+len)(lengthr-start -len))letto_stringr=letrecstrings l=function|Empty->l|Leafs->s::l|Concat(left,_,right,_,_)->strings(stringslright)leftinstring_of_string_list(strings[]r)letreciter f=function|Empty ->()|Leafs->STRING.iterfs|Concat(l,_,r,_,_)->iterfl;iterfrtype'aiter=E|Cof'aSTRING.t*int*'at*'aiterletreccons_iterst=matchswith|Empty->t|Leafs->C(s,0,Empty,t)|Concat(l,_llen,r,_rlen,_h)->cons_iter l(cons_iterrt)letrecrev_cons_iterst=matchswith|Empty->t|Leafs->C(s,(STRING.lengths-1),Empty,t)|Concat(l,_,r,_,_)->rev_cons_iterr(rev_cons_iterlt)letenum_nextl()=match!lwith|E->raiseBatEnum.No_more_elements|C(s,p,r,t)->ifp+1=STRING.lengthsthenl:=cons_iterrtelsel:=C(s,p+1,r,t);STRING.unsafe_getspletenum_backwards_nextl()=match!lwith|E->raiseBatEnum.No_more_elements|C(s,p,r,t)->ifp=0thenl:=rev_cons_iterrtelsel:=C(s,p-1,r,t);STRING.unsafe_getspletenum_countl()=letrecauxn=function|E->n|C(s,p,m,t)->aux(n+(STRING.lengths-p)+lengthm)tinaux0!lletrev_enum_countl()=letrecauxn=function|E->n|C(_s,p,m,t)->aux(n+(p+1)+lengthm)tinaux0!lletenumt=letrecmakel=letl=reflinletclone()=make!linBatEnum.make~next:(enum_nextl)~count:(enum_countl)~cloneinmake(cons_itertE)let backwardst=letrecmakel=letl=reflinletclone()=make!linBatEnum.make~next:(enum_backwards_nextl)~count:(rev_enum_countl)~cloneinmake(rev_cons_itertE)letof_enume=BatEnum.fold(funaccx->append_char xacc)emptyeletof_backwardse=BatEnum.fold(funaccx->prepend_charxacc)emptyeletiterifr=letrecauxfi=function|Empty->()|Leafs->forj=0toSTRING.lengths-1dof(i+j)(STRING.unsafe_getsj)done|Concat(l,cl,r,_,_)->auxfil;auxf(i+cl)rinauxf0rletrecrangeiterfstartlen=function|Empty->ifstart<>0||len<>0thenraise Out_of_bounds|Leafs->letn=start+leninletlens=STRING.lengthsinifstart>=0&&len>=0&&n<= lensthenfori=startton-1dof(STRING.unsafe_getsi)doneelseraiseOut_of_bounds|Concat(l,cl,r,cr,_)->ifstart<0||len<0||start +len >cl+crthenraiseOut_of_bounds;ifstart<clthenbeginlet upto=start+leninifupto<=clthenrangeiterfstartlenlelsebeginrangeiterfstart(cl-start)l;rangeiterf0(upto-cl)rendendelsebeginrangeiterf(start-cl)lenrendletrecfoldfa=function|Empty->a|Leafs->letacc=refainfori=0toSTRING.lengths-1doacc:=f!acc(STRING.unsafe_get si)done;!acc|Concat(l,_,r,_,_)->foldf(foldfal)rletfoldifav=letrecauxia=function|Empty->a|Leafs->letacc=refainfor j=0toSTRING.lengths-1doacc:=f(i+j)!acc(STRING.unsafe_getsj)done;!acc|Concat(l,cl,r,_,_)->aux(i+cl)(auxial)rinaux0avletfold_left=foldletfold_right(f:'a->'b->'b)(v:'at)(acc:'b):'b=letrecaux(acc:'b)=function|Empty->acc|Leafs->STRING.fold_rightfsacc|Concat(l,_,r,_,_)->aux(auxaccr)linauxaccvletreducefv=letacc=ref(getv0)inrangeiter(fune->acc:=f!acce)1(lengthv-1)v;!accletof_arraya=of_string(STRING.of_enum(BatArray.enuma))letto_arrayt=BatArray.of_enum(enumt)letof_container=of_stringletto_container=to_stringletappend=append_charletprepend=prepend_charletrecmapf=function|Empty ->Empty|Leafa->Leaf(STRING.mapfa)|Concat(l,cl,r,cr,h)->letl=mapflinletr=mapfrinConcat(l,cl,r,cr,h)letmapifv=letoff=ref0inmap(funx->f(BatRef.post_incroff)x)vletrecexistsf=function|Empty ->false|Leafa->letrecauxfaleni=(i<len)&&(f(STRING.unsafe_getai)||auxfalen(i+1))inaux fa(STRING.lengtha)0|Concat(l,_,r,_,_)->existsfl||existsfr(*$T exists
exists (fun x -> true) empty = false
exists (fun x -> false) (of_array [|0;1;2|]) = false
exists (fun x -> x mod 2 <> 0) (of_array [|0;1;2|]) = true
exists (fun x -> x mod 2 <> 0) (of_array [|0;2|]) = false
*)letrecfor_allf=function|Empty ->true|Leafa->letrecauxfaleni=(i>=len)||(f(STRING.unsafe_getai)&&auxfalen(i+1))inaux fa(STRING.lengtha)0|Concat(l,_,r,_,_)->for_allfl&&for_allfr(*$T for_all
for_all (fun x -> true) empty = true
for_all (fun x -> true) (of_array [|0;1;2|]) = true
for_all (fun x -> x mod 2 = 0) (of_array [|0;1;2|]) = false
for_all (fun x -> x mod 2 = 0) (of_array [|0;2|]) = true
*)letrecfind_optf=function|Empty ->None|Leafa->letrecauxfaleni=ifi>=lenthenNoneelse beginletx=STRING.unsafe_getaiiniffxthenSomexelseauxfalen(i+1)endinauxfa(STRING.lengtha)0|Concat(l,_,r,_,_)->beginmatchfind_optflwith|Some_asres->res|None->find_opt frend(*$Tfind_opt
find_opt (fun x -> true) empty = None
find_opt (fun x -> true) (of_array [|0;1;2|]) = Some 0
find_opt (fun x -> x mod 2 <> 0) (of_array [|0;1;2|]) = Some 1
find_opt (fun x -> x mod 2 <> 0) (of_array [|0;2|]) = None
*)letfindfv=matchfind_optfvwith|None->raiseNot_found|Somea->a(*$T find
try ignore (find (fun x -> true) empty); false with Not_found -> true
find (fun x -> true) (of_array [|0;1;2|]) = 0
find (fun x -> x mod 2 <> 0) (of_array [|0;1;2|]) = 1
try ignore (find (fun x -> x mod 2 <> 0) (of_array [|0;2|])); false with Not_found -> true
*)letfindifv=letoff=ref(-1)inignore (find(funx->letresult=fxinincroff;result)v);!offletpartitionpv=fold_left(fun(yes,no)x->ifpxthen(append xyes,no)else(yes,appendxno))(empty,empty)vletfind_allpv=fold_left(funaccx->ifpxthenappendxaccelseacc)emptyvletmemmv=trylet_=find((=)m)vintruewithNot_found->falseletmemqmv=trylet_=find((==)m)vintruewithNot_found ->falseletfirstv=getv0letlastv=getv(lengthv-1)letshiftv=firstv,subv1(lengthv-1)letpopv=lastv,subv0(lengthv-1)letto_listr=letrecauxacc=function|Empty ->acc|Leafa->STRING.fold_right(funxl->x::l)aacc|Concat(l,_,r,_,_)->aux(auxaccr)linaux[]rletfilter=find_allletfilter_map f=fold(funaccx->matchfxwith|None->acc|Somev->append vacc)Emptyletdestructive_setvix=letrecauxi=function|Empty->raiseOut_of_bounds|Leafs->ifi>=0&&i<STRING.lengthsthenSTRING.unsafe_setsixelseraiseOut_of_bounds|Concat(l,cl,r,_cr,_)->ifi<clthenauxilelseaux(i-cl)rinaux ivletof_listl=of_array(Array.of_listl)letinitnf=ifn<0||n>max_lengththeninvalid_arg"Vect.init";(* Create as many arrays as we need to store all the data *)letrecauxoffacc=ifoff>=nthenaccelselet len=minleaf_size(n-off)inletarr=Array.initlen(fun i->f(off+i))inaux(off+len)(arr::acc)inlet base=aux 0[]in(* And then concatenate them *)List.fold_left(fun(acc:'at)(array:'aarray)->concat(of_arrayarray)acc)(empty:'at)(base:'aarraylist)let print?(first="[|")?(last="|]")?(sep="; ")print_aoutt=BatEnum.print~first~last~sepprint_a out(enumt)module Labels =structletinitn~f=initnfletgetv~n=getvnletatv~n=atvnletsetv~n~elem=setvnelemlet modifyv~n~f=modifyvnfletsubv~m~n=subvmnletinsert~n~sub=insertnsublet remove~m~n=removemnletiter~f=iterfletiteri~f=iterifletmap~f=mapfletmapi~f=mapifletfor_all~f=for_allfletexists~f=existsfletfind~f=findfletmem~elem=memelemletmemq~elem=memqelemletfindi~f=findifletfilter~f=filterfletfilter_map~f=filter_mapfletfind_all~f=find_allfletpartition~f=partitionfletdestructive_setv~n~elem=destructive_set vnelemletrangeiter~f~m~n=rangeiterfmnletfold_left~f~init=fold_leftfinitletfold~f~init =foldfinitletreduce~f=reducefletfold_right~fv~init=fold_rightfvinitletfoldi~f~init =foldifinitend(*$inject end *)end