How to find length of lazy sequence without forcing realization?

佐手、 提交于 2019-12-01 16:13:48

I suppose it's due to the fact that usually there are other ways to find out the size.

The only sequence implementation I can think of now that could potentially do that, is some kind of map of an expensive function/procedure over a known size collection.

A simple implementation would return the size of the underlying collection, while postponing realization of the elements of the lazy-sequence (and therefore execution of the expensive part) until necessary.

In that case one knows the size of the collection that is being mapped over beforehand and can use that instead of the lazy-seq size.

It might be handy sometimes and that's why it's not impossible to implement, but I guess rarely necessary.

A. Webb

As inspired by soulcheck's answer, here is a lazy but counted map of an expensive function over a fixed size collection.

(defn foo [s f] 
  (let [c (count s), res (map f s)] 
    (reify 
      clojure.lang.ISeq 
        (seq [_] res) 
      clojure.lang.Counted 
        (count [_] c) 
      clojure.lang.IPending 
        (isRealized [_] (realized? res)))))


(def bar (foo (range 5) (fn [x] (Thread/sleep 1000) (inc x))))

(time (count bar))
;=> "Elapsed time: 0.016848 msecs"
;    5

(realized? bar)
;=> false


(time (into [] bar))
;=> "Elapsed time: 4996.398302 msecs"
;   [1 2 3 4 5]

(realized? bar)
;=> true

(time (into [] bar))
;=> "Elapsed time: 0.042735 msecs"
;   [1 2 3 4 5]
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!