ocaml - 创建具有累积总和的新列表

标签 ocaml

我正在努力解决这个问题

Exercise 8.3 Write a function that takes a list of numbers and returns the cumulative sum; that is, a new list where the ith element is the sum of the first i + 1 elements from the original list. For example, the cumulative sum of [1, 2, 3] is [1, 3, 6].

我编写了这段代码,据我所知,这是正确的。

let lastItem = function 
  | [] -> 0
  | l -> List.hd (List.rev l);;

let rec cumulativeSumActual accum input =
match input with
  | [] -> accum
  | hd::tl -> cumulativeSumActual (accum::[(lastItem accum) + hd]) tl;;

let cumulativeSum = cumulativeSumActual [];;

let output = cumulativeSum [1; 2; 3;];;

let printer item =
    print_int item
    print_string "\n";;

List.iter printer output

但我收到错误

user1@ubuntu:~/Documents/Programs$ ocamlc -o CumulativeList CumulativeList.ml
File "CumulativeList.ml", line 8, characters 33-38:
Error: This expression has type 'a list
       but an expression was expected of type 'a

然后我将代码更改为

  | hd::tl -> cumulativeSumActual (accum@[(lastItem accum) + hd]) tl;;

它成功了!

但我不明白为什么 cons 运算符不起作用,为什么新的列表追加操作起作用?

cons 运算符应该只是将一个新项目添加到列表中,然后将新列表作为递归调用的第一个参数返回?

发生什么事了?

最佳答案

你有这样的表达:

lastItem accum

lastItem 的参数类型是 'a list

因此,accum 的类型为'a list

运算符 :: 需要左侧有一个元素,右侧有一个列表,但您将其应用于左侧的列表,因此会出现错误。 @ 运算符允许在任意一侧都有一个列表,因此它工作得很好。

关于ocaml - 创建具有累积总和的新列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18691501/

相关文章:

random - 如何在 Ocaml 中随机选择一个元素?

OCaml:使用 Core Set 添加元素的惯用方法是什么?

graph - OCaml 中以**纯**函数方式实现图的 DFS 和 BFS

ocaml - 参数化模块类型

functional-programming - OCaml:模式匹配与 If/else 语句

ocaml - 关于查找文档

java instanceof 和 ocaml 匹配

ocaml - 如何在没有冗余匹配情况的情况下转换通用变体实例?

branch - OCaml分支信息

graphics - 实际使用 OCaml Graphics 更改文本大小