ocaml - 使用延续的列表的产品
问题描述
我的目标是编写一个 times 类型的函数int list -> int
,它接受一个int
s 列表,并使用 continuations返回一个int
这样的结果,即 that = 中所有s 的int
乘积。例如返回。int
int list
times [2;2;3]
12
这是我到目前为止所拥有的:
let times l =
let rec times' l c = match l with
| [] -> c []
| h::h2::t -> times' (h*h2::t) (fun r -> c ( r))
| h :: [] -> times' [] (fun r -> c (h::[]))
in
times' l (fun r -> r) ;;
我的代码有问题
它返回一个 int 列表,其中一个元素是结果(输入中所有
int
s 的乘法int list
)我觉得这并没有真正使用延续,这似乎是一个正常的尾递归函数,但我不确定,因为我仍然不太熟悉这种编程风格。
解决方案
您以递归调用的方式在参数中进行了计算,但您应该继续进行。对于 CPS,您应该做的是“增长”给定的延续。
let times l =
let rec aux l c =
match l with
| [] -> c 1 (* I assume that (times []) is one, and pass it to the next computation c. *)
| n::ns -> aux ns (fun x -> c (n * x)) (* In a new continuation: For a given value x, multiply by n, and pass it to the next computation c. *)
in aux l (fun r -> r)
此外,解释 CPS 和直接风格之间差异的示例,用Wikipedia中的“Continuation-passing style”编写,可能会有所帮助。
推荐阅读
- python - TypeError:预期的 str、bytes 或 os.PathLike 对象,而不是 Django 中的 JpegImageFile(或 PngImageFile)
- android - Android,Contacts Contract:存储和检索自定义数据
- node.js - 从 Watson Assistant 获取 turn_count
- javascript - 这个开玩笑的测试设置有什么问题?
- javascript - 如何在 JSDoc 和 TypeScript 中编写原型的参数类型?
- python - 如果用户提供相同的输入超过 X 时间打印一些东西
- swift - 如何防止浮动调色板窗口被视为文档
- r - 从光栅砖创建的数据框太大并且很多零值
- reactjs - 如何在 React 应用程序中重新渲染 Uppy 实例时保留我已经上传的图像的图像预览
- android - 谷歌云平台和 Firebase 存储有什么联系?