首页 > 解决方案 > 平方和的总和 OCaml

问题描述

我正在尝试使用我的 foldl 函数对浮点列表中两个连续元素的所有平方和求和。

let rec foldl (f: 'b -> 'a -> 'b) (accum: 'b) (lst: 'a list) : 'b = match lst with 
|[] -> accum
|x::xs -> foldl f (f accum x) xs 

let sum_sqrt_sums (mylist:  float list) : float = match mylist with
 |[] -> raise(Failure "Nope")
 |[x] -> raise(Failure "No!")
 |x::xs -> foldl (fun x y -> sqrt (x +. y)) x xs

我跑步时有两个不同的结果

sum_sqrt_sums [4.0; 2.0; 6.0; 3.0];;
- : float = 2.43039103901312092

sqrt(4.0 +. 2.0) +. sqrt(2.0 +. 6.0) +. sqrt(6.0 +. 3.0) ;;
- : float = 8.27791686752936862

我的 sum 函数中的逻辑有什么问题?

标签: ocaml

解决方案


你的函数sum_sqrt_sums不计算

sqrt(4.0 +. 2.0) +. sqrt(2.0 +. 6.0) +. sqrt(6.0 +. 3.0) 

sqrt (sqrt (sqrt(2.0 +. 4.0) +. 6.0) +. 3.0)

您想要做的是保留在累加器中看到的最后一个元素,以将其添加到下一个元素,并将它们的平方和添加到累加器:

let sum_sqrt_sums = function
  | [] | [_] -> raise(Failure "Nope")
  | x::xs -> 
     let _, res = foldl (fun (x, acc) y -> (y, sqrt (x +. y) +. acc)) (x, 0.) xs in
     res

作为旁注,您的 foldl 功能就是 List.fold_left 功能


更新(使用不同变量名的版本以避免混淆):

let sum_sqrt_sums = function
  | [] | [_] -> raise(Failure "Nope")
  | x::xs -> 
     let _, res = foldl (fun (e, acc) y -> (y, sqrt (e +. y) +. acc)) (x, 0.) xs in
     res

推荐阅读