ocaml - 平方和的总和 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 函数中的逻辑有什么问题?
解决方案
你的函数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
推荐阅读
- vba - 添加到每张幻灯片的文本框实际上添加了很多到每张幻灯片
- racket - 我什么时候应该使用 Rosette 的浅嵌入与深层嵌入进行程序合成?
- java - 为什么回到main后这个输出保持不变?
- java - com.android.tools.r8.errors.CompilationError:程序类型已经存在:androidx.versionedparcelable.NonParcelField
- java - Spring @EnableRetry 抛出 InternalAutoProxyCreator
- python - Python 中的 REST API 包装器
- css - CSS - transform: scale() 与元素大小无关
- python - 如何使用python知道复制过程(scp)是否完成?
- javascript - 在跟踪鼠标位置的同时编写旋转的嘎嘎声
- java - 为什么在这个逻辑中使用 -1,1,0?