Skip to content

Commit

Permalink
pvec: implement iter_rev directly
Browse files Browse the repository at this point in the history
c-cube committed Jan 8, 2024
1 parent 12ff380 commit b9cc91f
Showing 2 changed files with 27 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/pvec/containers_pvec.ml
Original file line number Diff line number Diff line change
@@ -268,6 +268,24 @@ let iteri f (self : 'a t) : unit =
f (i + tail_off) (Array.unsafe_get self.tail i)
done

let rec iter_rev_rec_ f (self : _ tree) =
match self with
| Empty -> ()
| Leaf a ->
for i = A.length a - 1 downto 0 do
f (Array.unsafe_get a i)
done
| Node a ->
for i = A.length a - 1 downto 0 do
iter_rev_rec_ f (Array.unsafe_get a i)
done

let iter_rev f (self : 'a t) : unit =
for i = A.length self.tail - 1 downto 0 do
f (Array.unsafe_get self.tail i)
done;
iter_rev_rec_ f self.t

let rec iteri_rev_rec_ f idx (self : _ tree) =
match self with
| Empty -> ()
@@ -294,12 +312,15 @@ let fold_lefti f x m =
iteri (fun i x -> acc := f !acc i x) m;
!acc

let foldi_rev f x m =
let fold_revi f x m =
let acc = ref x in
iteri_rev (fun i x -> acc := f !acc i x) m;
!acc

let fold_rev f x m = foldi_rev (fun acc _ x -> f acc x) x m
let fold_rev f x m =
let acc = ref x in
iter_rev (fun x -> acc := f !acc x) m;
!acc

let rec map_t f (self : _ tree) : _ tree =
match self with
4 changes: 4 additions & 0 deletions src/pvec/containers_pvec.mli
Original file line number Diff line number Diff line change
@@ -63,6 +63,9 @@ val drop_last : 'a t -> 'a t

val iter : ('a -> unit) -> 'a t -> unit

val iter_rev : ('a -> unit) -> 'a t -> unit
(** Iterate on elements but starting from the end. *)

val iteri : (int -> 'a -> unit) -> 'a t -> unit
(** Iterate on elements with their index, in increasing order. *)

@@ -72,6 +75,7 @@ val iteri_rev : (int -> 'a -> unit) -> 'a t -> unit
val fold_left : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b
val fold_rev : ('b -> 'a -> 'b) -> 'b -> 'a t -> 'b
val fold_lefti : ('b -> int -> 'a -> 'b) -> 'b -> 'a t -> 'b
val fold_revi : ('b -> int -> 'a -> 'b) -> 'b -> 'a t -> 'b

val append : 'a t -> 'a t -> 'a t
(** [append a b] adds all elements of [b] at the end of [a]. This is

0 comments on commit b9cc91f

Please sign in to comment.