首页 > 解决方案 > 如何在 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

标签: functional-programmingocaml

解决方案


您的流与列表极为相似,只是您需要调用一个函数来获取列表的尾部。

您提出的代码有很多缺陷。我看到的主要两个缺陷是:

  1. 您正在使用构造函数NoneSome而流具有构造函数NilCons.

  2. 您没有调用函数来获取流的尾部。请注意, inCons (a, b)b一个“流 thunk”,即,它是一个您可以调用以获取流的函数。

(也许这是仅有的两个缺陷:-)

我希望这有帮助。


推荐阅读