Skip to content

Commit

Permalink
feat(vector): add Vector.{filter,filter_map}_in_place
Browse files Browse the repository at this point in the history
  • Loading branch information
c-cube committed Jul 26, 2018
1 parent c800250 commit e530547
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
41 changes: 41 additions & 0 deletions src/core/CCVector.ml
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,24 @@ let map f v =
to_list (map string_of_int v) = ["1"; "2"; "3"]
*)

(*$QR
Q.(pair (fun1 Observable.int small_int) (small_list small_int)) (fun (Q.Fun (_,f),l) ->
let v = of_list l in
to_list (map f v) = List.map f l)
*)

let map_in_place f v =
iteri
(fun i x -> Array.unsafe_set v.vec i (f x))
v

(*$QR
Q.(pair (fun1 Observable.int small_int) (small_list small_int)) (fun (Q.Fun (_,f),l) ->
let v = of_list l in
map_in_place f v;
to_list v = List.map f l)
*)

let filter' p v =
let i = ref 0 in (* cur element *)
let j = ref 0 in (* cur insertion point *)
Expand Down Expand Up @@ -638,6 +656,29 @@ let filter_map f v =
to_list (filter_map f v) = CCList.filter_map f l)
*)

let filter_map_in_place f v =
let i = ref 0 in (* cur element *)
let j = ref 0 in (* cur insertion point *)
let n = v.size in
while !i < n do
match f v.vec.(!i) with
| None -> incr i (* drop *)
| Some y ->
(* move element i at the first empty slot.
invariant: i >= j*)
v.vec.(!j) <- y;
incr i;
incr j
done;
v.size <- !j

(*$QR
Q.(pair (fun1 Observable.int (option small_int)) (small_list small_int)) (fun (Q.Fun (_,f),l) ->
let v = of_list l in
filter_map_in_place f v;
to_list v = CCList.filter_map f l)
*)

let flat_map f v =
let v' = create () in
iter (fun x -> iter (push v') (f x)) v;
Expand Down
8 changes: 8 additions & 0 deletions src/core/CCVector.mli
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,10 @@ 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 map_in_place : ('a -> 'a) -> ('a,_) t -> unit
(** Map elements of the vector in place
@since NEXT_RELEASE *)

val filter : ('a -> bool) -> ('a,_) t -> ('a, 'mut) t
(** Filter elements from the vector. [filter p v] leaves [v] unchanged but
returns a new vector that only contains elements of [v] satisfying [p]. *)
Expand Down Expand Up @@ -172,6 +176,10 @@ val find_map : ('a -> 'b option) -> ('a,_) t -> 'b option
val filter_map : ('a -> 'b option) -> ('a,_) t -> ('b, 'mut) t
(** Map elements with a function, possibly filtering some of them out. *)

val filter_map_in_place : ('a -> 'a option) -> ('a,_) t -> unit
(** Filter-map elements of the vector in place
@since NEXT_RELEASE *)

val flat_map : ('a -> ('b,_) t) -> ('a,_) t -> ('b, 'mut) t
(** Map each element to a sub-vector. *)

Expand Down

0 comments on commit e530547

Please sign in to comment.