functional-programming - 如何在 Ocaml 中迭代流
问题描述
我正在尝试遍历流以打印内容。
type 'a stream = Nil | Cons of 'a * 'a stream thunk and 'a thunk = unit -> 'a
这是我的函数被调用的地方
|> iter_stream ~f:(fun (f,c,l) -> printf "%s %s %s\n" f c l)
这就是类型
let rec iter_stream st ~f
(* val iter_stream : 'a stream -> ('a -> unit) -> unit *)
我似乎找不到任何关于如何实现它的例子。我唯一的想法是将其视为一个显然错误的列表,因为我遇到类型错误。
let rec iter_stream st ~f =
match st with
| None -> ()
| Some(x, st') -> f x; iter_stream st' ~f
解决方案
您的流与列表极为相似,只是您需要调用一个函数来获取列表的尾部。
您提出的代码有很多缺陷。我看到的主要两个缺陷是:
您正在使用构造函数
None
,Some
而流具有构造函数Nil
和Cons
.您没有调用函数来获取流的尾部。请注意, in
Cons (a, b)
是b
一个“流 thunk”,即,它是一个您可以调用以获取流的函数。
(也许这是仅有的两个缺陷:-)
我希望这有帮助。
推荐阅读
- mysql - 查找其中一个与另一个相比购买了产品超集的所有客户对
- python - np.load() 在 for 循环中
- python-3.x - 使用```range()```函数-python3.8.0倒计时问题
- php - 中文字符的PHP问题
- javascript - 开放层 3 中的坐标基于什么以及它们如何工作?
- r - metafor rma.mv:与 random = list(~1 |id1, ~1 | id2) 不收敛,但 random = list(~ id1|id2)
- html - 我可以选择不显示图像的替代文字吗?我可以设置 alt 标签的样式吗?或者为非视障人士隐藏它们?
- python - 为列中的每个潜在值创建一个新列以创建与行值匹配的真值数组
- scala - scala: Async processing using Future.sequence
- mongodb - 为什么 MongoDB 在使用 findOneAndUpdate() 更新新文档时返回 value:null 错误?