Ocaml:懒惰列表

Nic*_*ner 8 ocaml stream lazy-evaluation

如何制作一个表示一系列加倍数的惰性列表?例:

1 2 4 8 16 32
Run Code Online (Sandbox Code Playgroud)

eph*_*ent 13

使用流:

let f x = Stream.from (fun n -> Some (x * int_of_float (2.0 ** float_of_int n)))
Run Code Online (Sandbox Code Playgroud)

要么

let f x =
  let next = ref x in
    Stream.from (fun _ -> let y = !next in next := 2 * y ; Some y)
Run Code Online (Sandbox Code Playgroud)

使用自定义lazy_list类型:

type 'a lazy_list =
  | Nil
  | Cons of 'a * 'a lazy_list lazy_t
let rec f x = lazy (Cons (x, f (2*x)))
Run Code Online (Sandbox Code Playgroud)


cho*_*ida 9

伟大的博客获得了广泛的关于这个主题的文章:

http://enfranchisedmind.com/blog/posts/ocaml-lazy-lists-an-introduction/

您还可以查看http://batteries.forge.ocamlcore.org/doc.preview%3Abatteries-beta1/html/api/Lazy%5Flist.html

这是处理此问题的标准库.

这个问题也与这个问题非常相似:

哪些OCaml库可用于惰性列表处理?