我在下面的代码中遇到语法错误:
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;;我面临的错误在这里
done; ^^^^ Error: Syntax error例如,代码应该总结每次迭代时列表的当前值
sum [1;2;3;4];; - : int list = [1; 3; 6; 10]所以我想我正在朝着正确的方向前进,我不明白的是为什么这个错误不断出现?
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 errorThe 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?
最满意答案
let counter语句中缺少关键字in 。
另一个会在之后弹出的错误: 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;;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;;更多推荐
发布评论