使用 map/reduce 在 Clojure 中实现斐波那契
是否可以使用reduce
在Clojure中高效地实现斐波那契数列? “累加器”包含什么?
我想它必须是懒惰的。很明显如何使用递归或循环/递归来做到这一点。
Is it possible to implement the fibonacci series in Clojure efficiently using reduce
? What would the "accumulator" contain?
I imagine that it will have to be lazy. It's obvious how to do it using recursion or loop/recur.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用一对连续的斐波那契值作为累加器,如下所示:
由于创建了大量中间对并使用多余的范围序列来驱动正确的迭代次数,这并不是特别有效,但它是 O( n) 从算法的角度来看(即与高效迭代解决方案相同,并且比朴素递归解决方案好得多)。
You could use a pair of successive fibonacci values as the accumulator, as follows:
This is not particularly efficient due to the creation of lots of intermediate pairs and use of the superfluous range sequence to drive the right number of iterations, but it is O(n) from an algorithmic perspective (i.e. the same as the efficient iterative solution, and much better than the naive recursive one).
不使用map/reduce,但迭代也可以避免递归。
在 Intel 2.4 Ghz 上这需要 21 毫秒
。在同一台机器上,reduce 需要 61 毫秒。不知道为什么迭代速度更快。
Not using map/reduce, but iterate can avoid recursion too.
This takes 21ms on an Intel 2.4 Ghz
On the same machine, reduce takes 61msec. Not sure why iterate is faster.