Ocaml:惰性列表
如何制作一个表示加倍数字序列的惰性列表?例子:
1 2 4 8 16 32
How can I make a lazy list representing a sequence of doubling numbers? Example:
1 2 4 8 16 32
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用流:
或
使用自定义
lazy_list
类型:Using streams:
or
Using a custom
lazy_list
type:另外,我的 OCaml 网络应用程序环境 中有一个名为
Cf_seq
的惰性列表模块核心基础。事实上,我写了一整套函数式数据结构。这一切都可以在 2 条款 BSD 许可证下使用。享受。更新:代码已重命名为“Oni”,现在托管在位桶。您还可以使用 GODI 包。
Also, there is a lazy list module called
Cf_seq
in my OCaml Network Application Environment Core Foundation. In fact, I wrote a whole passle of functional data structures. It's all available under a 2-clause BSD license. Enjoy.Update: the code has been renamed "Oni" and it's now hosted at BitBucket. You can also use the GODI package for it.
如果你想手动完成,我想说你必须主要选项:
使用自定义的
lazy_list
类型,就像ephemient所说的那样(除了他的解决方案有点破损):使用一种 thunk (就像用来实现惰性的东西 )以不支持它的语言进行评估)。您将列表定义为函数
unit -> 'a
说明如何从当前元素获取下一个元素(无需为此使用流)。例如,要定义所有自然整数的列表,您可以这样做如果你这样做
您将得到以下输出:
<前><代码>0
1
2
If you want to do it by hand, I'd say you have to main options:
Use a custom
lazy_list
type, like ephemient said (except his solution is a bit broken):Use a kind of thunk (like the thing used to implement lazy evaluation in a language that does not support it). You define your list as a function
unit -> 'a
that says how to get the next element from the current one (no need to use streams for that). For example, to define the list of all natural integers, you can doThe if you do
you will get the following output:
来自遥远未来的答案...
OCaml 4.07 引入了
Seq
模块< /a> 这可以促进这一点。Answer from the distant future...
OCaml 4.07 introduced the
Seq
module which can facilitate this.