bounded-count

added
1.9

ns
clojure.core

type
function

(bounded-count n coll)

If coll is counted? returns its count, else will count at most the first n
elements of coll using its seq

                ;;;; Length of a vector can be determined in constant time
;;;; so this always returns the actual length of the vector

(bounded-count 5 [1 2 3 4])
;;=> 4
(bounded-count 5 [1 2 3 4 5])
;;=> 5
(bounded-count 5 [1 2 3 4 5 6])
;;=> 6

;;;; Length of a lazy seq cannot be determined in constant time
;;;; so this counts at most the first 5 elements

(bounded-count 5 (map identity [1 2 3 4]))
;;=> 4
(bounded-count 5 (map identity [1 2 3 4 5]))
;;=> 5
(bounded-count 5 (map identity [1 2 3 4 5 6]))
;;=> 5
            
                ;;;; This would run forever

(count (range))

;;;; But this doesn't

(bounded-count 10000 (range))
;;=> 10000