Skip to content

Commit

Permalink
List.sum [] is now 0 (ocaml-batteries-team#916)
Browse files Browse the repository at this point in the history
List.sum and List.fsum default to 0 (or 0.0) in case the list is empty.
Previously, this was raising Invalid_argument.

Closes ocaml-batteries-team#519
  • Loading branch information
rixed authored and UnixJunkie committed Oct 1, 2019
1 parent 43068b3 commit 3c323ef
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 9 deletions.
5 changes: 3 additions & 2 deletions src/batArray.mlv
Original file line number Diff line number Diff line change
Expand Up @@ -592,12 +592,13 @@ let min_max a =
try ignore (min_max [||]); false with Invalid_argument _ -> true
*)

let sum = reduce (+)
let fsum = reduce (+.)
let sum = fold_left (+) 0
let fsum = fold_left (+.) 0.

(*$T sum
sum [|1;2;3|] = 6
sum [|0|] = 0
sum [||] = 0
*) (*$T fsum
fsum [|1.0;2.0;3.0|] = 6.0
fsum [|0.0|] = 0.0
Expand Down
6 changes: 4 additions & 2 deletions src/batList.mliv
Original file line number Diff line number Diff line change
Expand Up @@ -298,12 +298,14 @@ val min : 'a list -> 'a

val sum : int list -> int
(** [sum l] returns the sum of the integers of [l].
@raise Invalid_argument on the empty list.
Returns [0] on the empty list.
Note: prior to NEXT_RELEASE, used to raise Invalid_argument on the empty list.
*)

val fsum : float list -> float
(** [fsum l] returns the sum of the floats of [l].
@raise Invalid_argument on the empty list.
Returns [0.] on the empty list.
Note: prior to NEXT_RELEASE, used to raise Invalid_argument on the empty list.
*)

val favg : float list -> float
Expand Down
14 changes: 9 additions & 5 deletions src/batList.mlv
Original file line number Diff line number Diff line change
Expand Up @@ -1369,11 +1369,15 @@ let reduce f = function

let min l = reduce Pervasives.min l
let max l = reduce Pervasives.max l
let sum l = reduce (+) l
let sum l = fold_left (+) 0 l
(*$= sum & ~printer:string_of_int
2 (sum [1;1])
0 (sum [])
*)

let fsum l =
match l with
| [] -> invalid_arg "List.fsum: Empty List"
| [] -> 0.
| x::xs ->
let acc = ref x in
let rem = ref xs in
Expand All @@ -1386,9 +1390,9 @@ let fsum l =
rem := xs
done;
!acc
(*$T fsum
try let _ = fsum [] in false with Invalid_argument _ -> true
fsum [1.;2.;3.] = 6.
(*$= fsum & ~printer:string_of_float
0. (fsum [])
6. (fsum [1.;2.;3.])
*)

let favg l =
Expand Down

0 comments on commit 3c323ef

Please sign in to comment.