From a69612213144c442bc5c6f14fd5e29a5a9583966 Mon Sep 17 00:00:00 2001 From: Fardale Date: Sun, 17 Nov 2019 12:17:13 +0100 Subject: [PATCH] add CCVector.mapi --- src/core/CCVector.ml | 20 ++++++++++++++++++++ src/core/CCVector.mli | 5 +++++ 2 files changed, 25 insertions(+) diff --git a/src/core/CCVector.ml b/src/core/CCVector.ml index 3bde49e1..a58834ca 100644 --- a/src/core/CCVector.ml +++ b/src/core/CCVector.ml @@ -498,6 +498,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 42f4bd4e..905f33dd 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 *)