Why flaws are needed to prevent infinite recursion

When defining an infinite sequence, I noticed that cons are needed to avoid infinite recursion. However, I do not understand why. Here is the code in question:

(defn even-numbers
  ([] (even-numbers 0))
  ([n] (cons n (lazy-seq (even-numbers (+ 2 n))))))

(take 10 (even-numbers))
;; (0 2 4 6 8 10 12 14 16 18)

This works great; but since I like to ask questions, I started wondering why the cons are needed (except for the inclusion of 0). In the end, the lazy-seq function creates lazy seq. This means that the rest of the values ​​should not be calculated until they are called (or separated). So I tried it.

(defn even-numbers-v2
  ([] (even-numbers-v2 0))
  ([n] (lazy-seq (even-numbers-v2 (+ 2 n)))))

(take 10 (even-numbers-v2))
;; Infinite loooooooooop

So now I know that cons are needed, but I would like to know why cons are needed for a lazy assessment of an allegedly lazy sequence.

+4
1

Lazy seqs - seq, . cons - , clojure.core/concat "chunked conses" , , seq lazy-seq, - , , lazy-seq , - seq . .


, seq. , , " , - seq, ". , pokes seq ... ?

lazy-seq cons, , seq seq- , .

, , lazy-seq , ... , . , , (. ), , seq , .


, even-numbers-v2. lazy-seq, . , (n), ((+ 2 n)), - , seq. , seq, , ; , , ( , , + longs).

+7

All Articles