3
votes

For my prime numbers lazy seq, I am checking to see if an index value is divisible by all the primes 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)))
1
I'm not sure what you're asking here, the code seems to function and there is only one value for primes in your algorithm.Joost Diepenmaat
That's the problem. If you replace the output y in the last line with primes, then you'll see that primes is stuck at the initial value and not updated as it should be.Paul Lam

1 Answers

2
votes

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.