我试图使用我的 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
Run Code Online (Sandbox Code Playgroud)
我跑步时有两个不同的结果
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
Run Code Online (Sandbox Code Playgroud)
我的 sum 函数的逻辑有什么问题?
你的函数sum_sqrt_sums不计算
sqrt(4.0 +. 2.0) +. sqrt(2.0 +. 6.0) +. sqrt(6.0 +. 3.0)
Run Code Online (Sandbox Code Playgroud)
但
sqrt (sqrt (sqrt(2.0 +. 4.0) +. 6.0) +. 3.0)
Run Code Online (Sandbox Code Playgroud)
您要做的就是保留累加器中看到的最后一个元素,将其添加到下一个元素,并将它们的平方和添加到累加器中:
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
Run Code Online (Sandbox Code Playgroud)
(作为旁注,你的 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
Run Code Online (Sandbox Code Playgroud)