aboutsummaryrefslogtreecommitdiff
path: root/src/clojure/contrib/lazy_seqs.clj
diff options
context:
space:
mode:
Diffstat (limited to 'src/clojure/contrib/lazy_seqs.clj')
-rw-r--r--src/clojure/contrib/lazy_seqs.clj42
1 files changed, 25 insertions, 17 deletions
diff --git a/src/clojure/contrib/lazy_seqs.clj b/src/clojure/contrib/lazy_seqs.clj
index 118a5602..cf83b5de 100644
--- a/src/clojure/contrib/lazy_seqs.clj
+++ b/src/clojure/contrib/lazy_seqs.clj
@@ -33,24 +33,32 @@
(ns clojure.contrib.lazy-seqs
(:use clojure.contrib.def))
+; primes cannot be written efficiently as a function, because
+; it needs to look back on the whole sequence. contrast with
+; fibs and powers-of-2 which only need a fixed buffer of 1 or 2
+; previous values.
(defvar primes
- (lazy-cat [2 3 5 7]
+ (concat
+ [2 3 5 7]
+ (lazy-seq
(let [primes-from
- (fn primes-from [n [f & r]]
- (if (some #(zero? (rem n %))
- (take-while #(<= (* % %) n) primes))
- (recur (+ n f) r)
- (lazy-seq (cons n (primes-from (+ n f) r)))))
- wheel (cycle [2 4 2 4 6 2 6 4 2 4 6 6 2 6 4 2
- 6 4 6 8 4 2 4 2 4 8 6 4 6 2 4 6
- 2 6 6 4 2 4 6 2 6 4 2 4 2 10 2 10])]
- (primes-from 11 wheel)))
- "A lazy sequence of all the prime numbers.")
+ (fn primes-from [n [f & r]]
+ (if (some #(zero? (rem n %))
+ (take-while #(<= (* % %) n) primes))
+ (recur (+ n f) r)
+ (lazy-seq (cons n (primes-from (+ n f) r)))))
+ wheel (cycle [2 4 2 4 6 2 6 4 2 4 6 6 2 6 4 2
+ 6 4 6 8 4 2 4 2 4 8 6 4 6 2 4 6
+ 2 6 6 4 2 4 6 2 6 4 2 4 2 10 2 10])]
+ (primes-from 11 wheel))))
+ "Lazy sequence of all the prime numbers.")
+
+(defn fibs []
+ "Returns a lazy sequence of all the Fibonacci numbers."
+ (map first (iterate (fn [[a b]] [b (+ a b)]) [0 1])))
+
+(defn powers-of-2 []
+ "Returns a lazy sequence of all the powers of 2"
+ (iterate #(bit-shift-left % 1) 1))
-(defvar fibs
- (lazy-cat [0 1] (map + fibs (rest fibs)))
- "A lazy sequence of all the fibonacci numbers.")
-(defvar powers-of-2
- (lazy-seq (cons 1 (map #(bit-shift-left % 1) powers-of-2)))
- "A lazy sequence of all the powers of 2")