Skip to content

Commit

Permalink
Add CArray.fold_right
Browse files Browse the repository at this point in the history
  • Loading branch information
yallop committed Sep 19, 2016
1 parent 388a7a8 commit 3acdde2
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/ctypes/ctypes.mli
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,11 @@ sig
[(((x @ a.(0)) @ a.(1)) ...) @ a.(n-1)]
where [n] is the length of the array [a]. *)

val fold_right : ('b -> 'a -> 'a) -> 'b t -> 'a -> 'a
(** [CArray.fold_right f a x] computes
[a.(0) @ (a.(1) @ ( ... (a.(n-1) @ x) ...))]
where [n] is the length of the array [a]. *)

val length : 'a t -> int
(** Return the number of elements of the given array. *)

Expand Down
7 changes: 7 additions & 0 deletions src/ctypes/ctypes_memory.ml
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,13 @@ struct
r := f !r (unsafe_get a i)
done;
!r

let fold_right f a x =
let r = ref x in
for i = length a - 1 downto 0 do
r := f (unsafe_get a i) !r
done;
!r
end

let make ?finalise s =
Expand Down
16 changes: 16 additions & 0 deletions tests/test-arrays/test_array.ml
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,19 @@ let test_fold_left _ =
assert_equal r []


(*
Test the CArray.fold_right function
*)
let test_fold_right _ =
let a = CArray.of_list int [1; 2; 3] in
let r = CArray.fold_right (Printf.sprintf "%d%s") a "." in
assert_equal "123." r;

let a = CArray.of_list int [] in
let r = CArray.fold_right (fun _ -> assert false) a [] in
assert_equal r []


(*
Test that creating an array initializes all elements appropriately.
*)
Expand Down Expand Up @@ -270,6 +283,9 @@ let suite = "Array tests" >:::
"CArray.fold_left"
>:: test_fold_left;

"CArray.fold_right"
>:: test_fold_right;

"array initialization"
>:: test_array_initialiation;

Expand Down

0 comments on commit 3acdde2

Please sign in to comment.