ClojureDocs

Nav

Namespaces

range

clojure.core

Available since 1.0 (source)
  • (range)
  • (range end)
  • (range start end)
  • (range start end step)
Returns a lazy seq of nums from start (inclusive) to end
(exclusive), by step, where start defaults to 0, step to 1, and end to
infinity. When step is equal to 0, returns an infinite sequence of
start. When start is equal to end, returns empty list.
5 Examples
;; default value of 'end' is infinity
user=> (range)
(0 1 2 3 4 5 6 7 8 9 10 ... 12770 12771 12772 12773 ... n)

;; Since clojure 1.2:
user=> (take 10 (range))
(0 1 2 3 4 5 6 7 8 9)

user=> (range 10)
(0 1 2 3 4 5 6 7 8 9)

user=> (range -5 5)
(-5 -4 -3 -2 -1 0 1 2 3 4)

user=> (range -100 100 10)
(-100 -90 -80 -70 -60 -50 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90)

user=> (range 0 4 2)
(0 2)

user=> (range 0 5 2)
(0 2 4)

user=> (range 0 6 2)
(0 2 4)

user=> (range 0 7 2)
(0 2 4 6)

user=> (range 100 0 -10)
(100 90 80 70 60 50 40 30 20 10)

user=> (range 10 -10 -1)
(10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9)
 

;; Since clojure 1.2:

user=> (take 10 (range))
(0 1 2 3 4 5 6 7 8 9)
;; finite range over java Integers
user=> (take 5 (range 42 (java.lang.Integer/MAX_VALUE)))
(42 43 44 45 46)

;; infinite range starting at a certain point
user=> (take 5 (drop 42 (range)))
(42 43 44 45 46)
;; Using a double as the value of step can produce an unexpected extra value.
;; In the second example below, there's an extra final value that's almost = 0.8.

(range 0 0.8 1/10)
(0 1/10 1/5 3/10 2/5 1/2 3/5 7/10)

user=> (range 0 0.8 0.1)
(0 0.1 0.2 0.30000000000000004 0.4 0.5 0.6 0.7 0.7999999999999999)

;; It's difficult to guess when this behavior will occur, unless you know
;; whether the double representation of step plus what "should" be the
;; last number is in fact less than end.  From the second example above, you 
;; can see that the extra value won't be included if you replace 0.8 by a 
;; number in 0.1, ..., 0.7 (e.g. since 0.7 is not less than 0.7) but you 
;; wouldn't necessarily know that you will get the extra value for end = 0.9,
;; 1.0, 1.1, but not for end = 1.2.
user=> (range 0 0)
()

user=> (range 0 1)
(0)
See Also

Returns a lazy sequence of the first n items in coll, or all items if there are fewer than n. Ret...

Added by MicahElliott

Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of side-effects

Added by MicahElliott
0 Notes
No notes for range