【问题标题】:How to iterate a stream in Ocaml如何在 Ocaml 中迭代流
【发布时间】:2020-09-14 19:34:49
【问题描述】:

我正在尝试遍历流以打印内容。

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-programming ocaml


【解决方案1】:

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

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

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

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

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

我希望这会有所帮助。

【讨论】:

  • 哦,我明白了。使用 Some and None 查看我的流的类型确实非常随机。我现在遇到的问题是我不知道如何让流的尾部将其作为参数传递给递归函数。在这种情况下,当我将流与 Cons(x, st') 匹配时,当我查看类型 st' 在这种情况下是一个'流 thunk。我如何将'流 thunk 变成'流。
猜你喜欢
  • 1970-01-01
  • 2015-06-28
  • 1970-01-01
  • 1970-01-01
  • 2022-12-07
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多