Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum a list of float numbers in OCaml

Tags:

ocaml

I am puzzled with my code:

let sum l = match l with
  | [] -> 0.0
  | h::t -> h +. (sum t);;

It should give me the sum of the numbers in the list. However when I check the code, I found the second code crashes when I use a list of length greater than or equal to 7. Here is the code:

# sum [0.;1.;2.;3.;4.;5.;]

- : float = 15.

# sum [0.;1.;2.;3.;4.;5.;6.]

- : float = 21.
# sum [0.;1.;2.;3.;4.;5.;6.;7.]

- : float = 21.

I am really confused because a modification of it, which operates on int, turned out to be normal:

let rec sumf l = match l with
  | []-> 0.0
  | h::t-> (float_of_int h) +. sumf t;;

and I do not know what is the essential difference between the two aside from I cast int into float in the second code.

like image 371
Bombyx mori Avatar asked Nov 15 '25 16:11

Bombyx mori


2 Answers

let sum l=
match l with
[]->0.0
|h::t-> h+. (sum t);;

Since you didn't use the rec keyword here, the call to sum in the last line is a call to a sum function that you defined beforehand. Apparently that sum function was buggy.

like image 74
Gilles 'SO- stop being evil' Avatar answered Nov 17 '25 09:11

Gilles 'SO- stop being evil'


I don't understand why your code crashes. When I try your sum function with rec keyword, I don't have any problem, otherwise you can't call recursively the sum function.

let rec sum l = 
  match l with 
   [] -> 0. 
  | h :: t -> h +. (sum t);;

You can also use the fold_left function in module List:

let sum l = List.fold_left (+.) 0. l;;
like image 25
Çağdaş Bozman Avatar answered Nov 17 '25 08:11

Çağdaş Bozman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!