Ocaml在一个整数列表中总结值(Ocaml summing up values in an integer list)

编程入门 行业动态 更新时间:2024-10-27 16:38:36
Ocaml在一个整数列表中总结值(Ocaml summing up values in an integer list)

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

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 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?

最满意答案

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;;

更多推荐

本文发布于:2023-08-04 03:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1408779.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   列表中   Ocaml   summing   list

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!