Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all realized values from a lazy seq

Tags:

clojure

;; create lazy infinite seq of random ints
(def infi-seq (repeatedly #(rand-int 11)))
(take 5 infi-seq) ; => (8 2 9 9 5)

How can I get all values realized (8 2 9 9 2) without knowing that the first five values have been realized?

like image 247
deadghost Avatar asked Mar 18 '23 15:03

deadghost


1 Answers

This should do the trick:

(defn take-realized
  [coll]
  (if-not (instance? clojure.lang.IPending coll)
    (cons (first coll) (take-realized (rest coll)))
    (when (realized? coll)
       (cons (first coll) (take-realized (rest coll))))))
like image 64
DanLebrero Avatar answered Mar 28 '23 09:03

DanLebrero