增加列表元素的总和

increasing sum of the elements of a list

如何计算列表中每个元素的总和乘以它在 OCaml 中的索引位置?示例:对于 [4;7;9],结果为 45 (4x1 + 7x2 + 9x3 = 45)。唯一授权的功能是 List.hd、List.tl 和 List.length.

我可以用这段代码在另一个方向上做:

let  rec sum l =
    let n = (List.length l) + 1    in 
    if l = [] then 0 else
     ((List.hd l)*(n-1))+ (sum(List.tl l)) ;;

sum [4;7;9];;
- : int = 35  (4x3 + 7x2 + 9x1 = 35)

但预期结果是 45 (4x1 + 7x2 + 9x3 = 45)。 谢谢你的帮助。

就个人而言,我可能会做这样的事情..

let rec new_sum l n =
  match l with
  | [] -> 0
  | head::tail -> (head * n) + new_sum tail (n+1)

let sum l =
  new_sum l 1;;
  
sum [4;7;9] 

...如果您不喜欢模式匹配的守卫,而更喜欢List.hdList.tlList.length,那么您可以使用...

let rec new_sum l n =
  if (List.length l == 0) then 0
  else ((List.hd l) * n) + new_sum (List.tl l) (n+1)

let sum l =
  new_sum l 1;;
  
sum [4;7;9];