How to get a sequence of numbers in a sorted set that are between two integers in clojure?

Let's say I have a sorted set of integers, xs, and I want to get all the integers in xs that are [x, y), i.e. between x and y.

I can do:

(select #(and (>= % x) (< % y)) xs) 

But this is inefficient - O (n), when it could be O (log n), I expect the number of returned items to be small. Using take-while and drop-while would allow me to exit as soon as I reached y, but I still can't efficiently go to x.

I am just learning clojure, here is how to do it in C ++:

 set<int>::iterator first = xs.lower_bound(x); set<int>::iterator last = xs.lower_bound(y); for (; first != last; ++first) // do something with *first 

Can I do this in clojure?

+6
clojure
source share
1 answer

Oops! I missed the subseq function, the link to it is missing on the documentation data structures page.

 (subseq xs >= x < y) 
+8
source share

All Articles