我正在努力解决这个问题
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/