Clojure's range function is inclusive from the start
and exclusive in the end
(if provided). Is there a function somewhere in the core library that will provide a fully inclusive (start & end) range?
I find code that has to adjust the end value in certain scenarios - such as a range going downwards rather than upwards (say in a list comprehension) much less readable. E.g.:
(range n -1 -1)
Am I just missing it in the docs or is there a cleaner way to do this?
I have some fondness for the guava Range API, so I was looking for something of similar flexibility.
There is no standard inclusive-range
function - following Kevin Ingle's terminology .
You can build one on top of range
:
(defn inclusive-range
([] (range))
([end] (range (inc end)))
([start end] (range start (inc end)))
([start end step] (range start (+ end step) step)))
But you run into trouble with ragged ends. For example,
(inclusive-range 10 11.5)
;(10 11 12)
Not what you want, I think.
maybe you want to write some function like this:
(defn my-range [start & {:keys [up-to down-to]}]
(cond (and (nil? up-to) (nil? down-to)) (range (inc start))
(nil? down-to) (range start (inc up-to))
:else (range start (dec down-to) -1)))
user> (my-range 10)
(0 1 2 3 4 5 6 7 8 9 10)
user> (my-range 0 :up-to 10)
(0 1 2 3 4 5 6 7 8 9 10)
user> (my-range 10 :down-to -10)
(10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10)
It is slightly more verbose, but it conforms to a simlpe range behaviour, and adds some sugary syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With