Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ocaml summing up values in an integer list

Tags:

syntax

ocaml

I'm facing a syntax error in the code below:

let sum list =
let current_sum = List.hd list in
for i = 1 to List.length list - 1 do
let counter = List.nth list i
    current_sum = current_sum + counter 
done;;

The error that I'm facing is here

done;
^^^^
Error: Syntax error

The code is supposed to sum up the current values of the list at each iteration, for example

sum [1;2;3;4];;
- : int list = [1; 3; 6; 10]

So I think I'm going about this in the right direction, what I don't understand is why this error keeps popping up?

like image 211
Ibo Avatar asked Nov 03 '25 08:11

Ibo


1 Answers

The keyword in is missing in the let counter statement.

Another error that will pop after : current_sum is immutable. You will have to change this.

Another way to achieve your sum : use List.fold function.

Putting in shape the comments below :

let sum_l l = 
   let (r,_) = List.fold_left 
      (fun (a_l, a_i) x -> ((a_i + x) :: a_l , a_i+x))
      ([],0) l in
   List.rev r;;
like image 85
Pierre G. Avatar answered Nov 05 '25 14:11

Pierre G.



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!