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?
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;;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With