diff --git a/src/core/CCVector.ml b/src/core/CCVector.ml index c8d63cff..1fa696b8 100644 --- a/src/core/CCVector.ml +++ b/src/core/CCVector.ml @@ -497,6 +497,26 @@ let map f v = to_list (map f v) = List.map f l) *) +let mapi f v = + if array_is_empty_ v + then create () + else ( + let vec = Array.init v.size (fun i -> f i (Array.unsafe_get v.vec i)) in + { size=v.size; vec; } + ) + +(*$T mapi + let v = create() in push v 1; push v 2; push v 3; \ + to_list (mapi (fun i e -> Printf.sprintf "%i %i" i e) v) = ["0 1"; "1 2"; "2 3"] +*) + +(*$QR mapi + Q.(pair (fun2 Observable.int Observable.int small_int) (small_list small_int)) + (fun (Q.Fun (_,f),l) -> + let v = of_list l in + to_list (mapi f v) = List.mapi f l) +*) + let map_in_place f v = iteri (fun i x -> Array.unsafe_set v.vec i (f x)) diff --git a/src/core/CCVector.mli b/src/core/CCVector.mli index 84d25709..24d93821 100644 --- a/src/core/CCVector.mli +++ b/src/core/CCVector.mli @@ -141,6 +141,11 @@ val iteri : (int -> 'a -> unit) -> ('a,_) t -> unit val map : ('a -> 'b) -> ('a,_) t -> ('b, 'mut) t (** Map elements of the vector, yielding a new vector. *) +val mapi : (int -> 'a -> 'b) -> ('a,_) t -> ('b, 'mut) t +(** [map f v] is just like {!map}, but it also passes in the index + of each element as the first argument to the function [f]. + @since NEXT_RELEASE *) + val map_in_place : ('a -> 'a) -> ('a,_) t -> unit (** Map elements of the vector in place @since 2.3 *)