1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798moduleA=Stdlib.ArrayincludeAopenBase(** [for_all2 p a1 a2] checks if the corresponding elements of arrays [a1] and
[a2] satisfy the predicate [p]. The [Invalid_argument] exception is raised
if the arrays do not have the same size. *)letfor_all2:('a->'b->bool)->'aarray->'barray->bool=funfa1a2->(*let exception Done in
let f x y = if not (f x y) then raise Done in
try iter2 f a1 a2; true with Done -> false*)(*code taken from Stdlib:*)letn1=lengtha1andn2=lengtha2inifn1<>n2theninvalid_arg"Array.for_all2"elseletrecloopi=ifi=n1thentrueelseiff(unsafe_geta1i)(unsafe_geta2i)thenloop(succi)elsefalseinloop0(** [pp elt sep ppf a] prints the array [a] on the formatter [ppf] using
[sep] as separator and [elt] for printing the elements. *)letpp:'app->string->'aarraypp=funeltsepoca->letn=A.lengthainifn>0theneltoc(A.geta0);fori=1ton-1dooutoc"%s%a"sepelt(A.getai)done(** Comparison function on arrays. *)letcmp:'acmp->'aarraycmp=funcmp_elt->letcmpa1a2(* of the same length *)=letexceptionDistinctofintinletreccmpi=ifi>=0thenmatchcmp_elt(A.geta1i)(A.geta2i)with|0->cmp(i-1)|n->raise(Distinctn)intrycmp(A.lengtha1-1);0withDistinctn->ninfuna1a2->ifa1==a2then0elselex(cmp_mapStdlib.compareA.length)cmp(a1,a1)(a2,a2)(** [eq eq_elt a1 a2] tests the equality of [a1] and [a2], comparing their
elements with [eq_elt]. *)leteq:'aeq->'aarrayeq=funeq_elta1a2->a1==a2||(A.lengtha1=A.lengtha2&&for_all2eq_elta1a2)(** [max_index ?cmp a] returns the index of the first maximum of array [a]
according to comparison [?cmp]. If [cmp] is not given, defaults to
[Stdlib.compare]. *)letmax_index:?cmp:('a->'a->int)->'aarray->int=fun?(cmp=Stdlib.compare)arr->letlen=A.lengtharriniflen=0theninvalid_arg"Extra.Array.max_index"elseletmax=ref0infori=1tolen-1doifcmp(A.getarr!max)(A.getarri)<0thenmax:=idone;!max(** [max ?cmp a] returns the higher element according to comparison function
[?cmp], using [Stdlib.compare] if not given, in array [a]. *)letmax:?cmp:('a->'a->int)->'aarray->'a=fun?(cmp=Stdlib.compare)arr->A.getarr(max_index~cmparr)(** [unzip a] is [List.unzip (Array.to_list a)]. *)letunzip:('a*'b)array->'alist*'blist=funa->letaux(el,er)(accl,accr)=(el::accl,er::accr)inA.fold_rightauxa([],[])(** [drop n a] discards the first [n] elements of [a]. The empty array is
returned if [n > length a]. *)letdrop:int->'aarray->'aarray=funna->letl=lengthainifn>=lthen[||]elseA.suban(l-n)(** Array.fold_left_map is a combination of Array.fold_left and Array.map that
threads an accumulator through calls to f, since OCaml 4.13. *)letfold_left_mapfaccinput_array=letlen=lengthinput_arrayiniflen=0then(acc,[||])elsebeginletacc,elt=facc(unsafe_getinput_array0)inletoutput_array=A.makeleneltinletacc=refaccinfori=1tolen-1doletacc',elt=f!acc(unsafe_getinput_arrayi)inacc:=acc';unsafe_setoutput_arrayielt;done;!acc,output_arrayend