本文介绍了Clojure和Python中的Lazy无限序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是最好的实现,我可以找到的懒惰无限序列的斐波那契数字在Clojure和Python:

Here are the best implementations I could find for lazy infinite sequences of Fibonacci numbers in both Clojure and Python:

Clojure:

(def fib-seq (lazy-cat [0 1]
 (map + fib-seq (rest fib-seq))))

示例用法:

 (take 5 fib-seq)

Python:

def fib():
 a = b = 1
 while True:
  yield a
  a,b = b,a+b

示例用法:

for i in fib():
  if i > 100:
    break
  else:
    print i

Python代码更直观。

Obviously the Python code is much more intuitive.

我的问题是:在Clojure中有更好的(更直观和简单)的实现吗?

My question is: Is there a better (more intuitive and simple) implementation in Clojure ?

我在
开启后续问题

推荐答案

>

I like:

(def fibs
  (map first
       (iterate
           (fn [[ a, b       ]]
                [ b, (+ a b) ])
           [0, 1])))


$ b b

这似乎与python / generator版本有一些相似之处。

Which seems to have some similarities to the python/generator version.

这篇关于Clojure和Python中的Lazy无限序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 11:13
查看更多