Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

BatArray.remove_at #996

Merged
merged 1 commit into from
Dec 23, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/batArray.mliv
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,12 @@ val insert : 'a array -> 'a -> int -> 'a array
@raise Invalid_argument
if [i < 0 || i > Array.length xs]. *)

val remove_at : int -> 'a array -> 'a array
(** [remove_at i a] returns the array [a] without the element at index [i].

@raise Invalid_argument if [i] is outside of [a] bounds.
@since NEXT_RELEASE *)

(** {6 Boilerplate code}*)

val print : ?first:string -> ?last:string -> ?sep:string ->
Expand Down
16 changes: 16 additions & 0 deletions src/batArray.mlv
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,22 @@ let insert xs x i =
with Invalid_argument _ -> true
*)

let remove_at i src =
let x = src.(i) in (* keep the bound check in there *)
let n = length src in
let dst = make (n - 1) x in
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the record: In theory, Array.init would permit to initialize dst only once taher than twice (first with x, second with actual values). In practice IIRC it's the same under the hood.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought about this.
If it's faster, why not.
I think it might also make the code more readable.
Thanks for the review by the way.

blit src 0 dst 0 i;
blit src (i + 1) dst i (n - i - 1);
dst
(*$T remove_at
try remove_at 0 [||] = [|1|] \
with Invalid_argument _ -> true
remove_at 0 [|1;2;3|] = [|2;3|]
remove_at 1 [|1;2;3|] = [|1;3|]
remove_at 2 [|1;2;3|] = [|1;2|]
try remove_at 3 [|1;2;3|] = [|1|] \
with Invalid_argument _ -> true
*)

(* helper function; only works for arrays of equal length *)
let eq_elements eq_elt a1 a2 = for_all2 eq_elt a1 a2
Expand Down