Ocaml:懒惰列表 [英] Ocaml: Lazy Lists
本文介绍了Ocaml:懒惰列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何制作一个懒惰的列表来表示一个双倍的数字序列?示例:
How can I make a lazy list representing a sequence of doubling numbers? Example:
1 2 4 8 16 32
推荐答案
使用流:
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)))
这篇关于Ocaml:懒惰列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文