开发者

How to call the lazy-seq made so far within construction of a lazy-seq?

开发者 https://www.devze.com 2023-03-12 20:48 出处:网络
For my prime numbers lazy seq, I am checking to see if an index value is divisible by all the p开发者_StackOverflowrimes below that current index (prime?). The problem is, when I call primes within it

For my prime numbers lazy seq, I am checking to see if an index value is divisible by all the p开发者_StackOverflowrimes below that current index (prime?). The problem is, when I call primes within itself (primes within shr-primes line), it only returns the initial value. Is it possible to keep the lazy-seq updated while building it lazily? It seems counter-intuitive to the lazy-seq concept.

(def primes
  (cons 2 (for [x           (range)
                  :let  [y                      (-> x (* 2) (+ 3))
                        root                    (math/floor (math/sqrt y))
                        shr-primes      (take-while (partial >= root) primes)   ;; primes stuck at init value
                        prime?              (every? #(not= % 0) (pmap #(rem y %) shr-primes))]
                  :when prime?]
              y)))


If you're doing the Project Euler problems, I don't want to spoil the exercise for you, but here's how you would define a Fibonacci sequence so that the lazy-seq keeps "updating" itself as it goes:

(defn fib-maker
  ([] (concat [0 1] (fib 0 1)))
  ([a b] (lazy-seq (cons b (fib b (+ a b))))))

(def fib (fib-maker))

I've used the above approach to implement the prime number sequence you've outlined above, so if you want more details let me know. Meanwhile, this will hopefully be a helpful hint.

0

精彩评论

暂无评论...
验证码 换一张
取 消