How to forget the head (GC'd) for lazy sequences in Clojure?

Let's say I have a huge lazy seq one and I want to repeat it so that I can process the data that I receive during the iteration.

The thing is, I want to lose my head (GC'd) from lazy seq(which is being processed), so I can work on seqs that have millions of data without OutofMemoryException.

I have 3 examples that I am not sure.

Could you provide best practices (examples) for this purpose?

Are these features lost?

Example 1

(defn lose-head-fn
  [lazy-seq-coll]
  (when (seq (take 1 lazy-seq-coll))
    (do
      ;;do some processing...(take 10000 lazy-seq-coll)
      (recur (drop 10000 lazy-seq-coll)))))

Example 2

(defn lose-head-fn
  [lazy-seq-coll]
  (loop [i lazy-seq-coll]
    (when (seq (take 1 i))
      (do
        ;;do some processing...(take 10000 i)
        (recur (drop 10000 i))))))

Example 3

(doseq [i lazy-seq-coll]
  ;;do some processing...
  )

Update: There is also an explanation in this answer here

+4
2

, ( , , doseq doc , ).

, lazy-seq-coll , - def let , . (lose-head-fn (range)) ,

(def r (range)) 

(lose-head-fn r) 
,

.

, , - def ( ) , var.

+4

, , , seq, , .

:

(let [nums (range)
      first-ten (take 10 nums)]
  (+ (last first-ten) (nth nums 100000000)))
=> 100000009

2 . ? - , + :

;; Don't do this!
(let [nums (range)
      first-ten (take 10 nums)]
  (+ (nth nums 100000000) (last first-ten)))

, / , htop , , ( 1G ).

?

, seq clojure . first-ten +. , nth - ( , ), first-ten , , , .

, , (last first-ten), first-ten . nums. nth , , , , , , nth , , , , .

:

;; Don't do this!
(let [nums (range)]
  (time (nth nums 1e8))
  (time (nth nums 1e8)))

, ? ( ) ( (time (nth nums 1e8))), , nums . nth, , :

(let [nums (range)]
  (time (nth nums 1e8))
  (time (nth (range) 1e8)))
"Elapsed time: 2127.814253 msecs"
"Elapsed time: 2042.608043 msecs"

, , , , - ( ), .

+2

Source: https://habr.com/ru/post/1679431/


All Articles