pvec: implement iter_rev directly

This commit is contained in:
Simon Cruanes 2024-01-07 23:21:32 -05:00
parent 12ff3802ce
commit b9cc91fb96
No known key found for this signature in database
GPG key ID: EBFFF6F283F3A2B4
2 changed files with 27 additions and 2 deletions

View file

@ -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

View file

@ -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