Ocaml 对整数列表中的值求和

Ibo*_*Ibo 3 syntax ocaml

我在下面的代码中遇到语法错误:

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;;
Run Code Online (Sandbox Code Playgroud)

我面临的错误在这里

done;
^^^^
Error: Syntax error
Run Code Online (Sandbox Code Playgroud)

代码应该在每次迭代时总结列表的当前值,例如

sum [1;2;3;4];;
- : int list = [1; 3; 6; 10]
Run Code Online (Sandbox Code Playgroud)

所以我认为我正在朝着正确的方向前进,我不明白为什么这个错误不断出现?

Pie*_* G. 5

语句中in缺少关键字let counter

在 : 之后弹出的另一个错误current_sum是不可变的。你将不得不改变这一点。

实现总和的另一种方法:使用 List.fold 函数。

整理下面的评论:

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;;
Run Code Online (Sandbox Code Playgroud)