8
A
回答
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
这是标准库处理这一。
这个问题也很类似于这样的问题:
13
使用流:
let f x = Stream.from (fun n -> Some (x * int_of_float (2.0 ** float_of_int n)))
或
let f x =
let next = ref x in
Stream.from (fun _ -> let y = !next in next := 2 * y ; Some y)
使用自定义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)))
1
如果你想通过做手工,我说你必须主要选项:
使用自定义
lazy_list
型,如ephemient说(除了他的解决方案是一个有点坏) :type 'a lazy_list = | Nil | Cons of 'a * 'a lazy_list let head = function | Nil -> failwith "Cannot extract head of empty list" | Cons (h, _) -> h let tail = function | Nil -> failwith "Cannot extract tail of empty list" | Cons (_, t) -> t
用一种thunk的(如用于实现在不支持此功能的语言懒评价的东西)。你可以将你的列表定义为函数
unit -> 'a
,该函数说明如何从当前元素获取下一个元素(不需要为此使用流)。例如,定义所有自然数的列表,如果你做print_int (naturals()); print_int (naturals()); print_int (naturals())
,你会得到下面的输出,你可以做
let make_lazy_list initial next = let lazy_list current() = let result = !current in current := (next !current); result in lazy_list (ref initial) let naturals = make_lazy_list 0 (function i -> i + 1)
的:
0 1 2
3
此外,在我的OCaml Network Application Environment核心基金会中有一个名为Cf_seq
的懒惰列表模块。实际上,我写了一整套函数式数据结构。它全部在2分条款的BSD许可下提供。请享用。
相关问题
- 1. 在ocaml中的懒惰评价
- 2. 懒惰过滤列表
- 3. 懒惰的素数列表
- 4. Elixir懒惰列表理解?
- 5. jQuery Mobile懒惰加载列表项
- 6. 在图库中使用懒惰列表
- 7. 懒惰列表的好分区实现?
- 8. Grails:懒惰列表的问题
- 9. json数据与懒惰列表
- 10. 片段中的懒惰列表
- 11. F#懒惰评估与非懒惰
- 12. 懒惰评价不那么懒惰?
- 13. Clojure素数懒惰序列
- 14. Java正则表达式懒惰操作符不那么懒惰?
- 15. 懒惰选择
- 16. hGetContents太懒惰
- 17. preg_match懒惰?
- 18. 关于懒惰
- 19. 懒惰评价
- 20. 是getLine懒惰?
- 21. 懒惰SlidingDrawer
- 22. 从非IO列表创建懒惰IO列表
- 23. Swift中的懒惰
- 24. SimpleInjector RegisterAll懒惰地
- 25. C#懒惰问题
- 26. 懒惰在C++ 11
- 27. PHP懒惰评估
- 28. 懒惰加载flexslider
- 29. Hadoop的懒惰distributedcache
- 30. GWT懒惰加载
你是指懒惰列表的一些特定实现,或者只是一般概念?另外,你是否真的需要懒惰_lists_(其中的值,一旦计算出来,被记住),或者你真的只想要一个流(其中值不记忆,因此只能被读取一次)? – 2009-10-27 16:43:52
我在找流。 – 2009-10-27 16:44:34