How do I get the sequence of numbers in a sorted-set that are between two integers in clojure?

Posted by Greg Rogers on Stack Overflow See other posts from Stack Overflow or by Greg Rogers
Published on 2010-06-03T04:42:44Z Indexed on 2011/11/30 1:51 UTC
Read the original article Hit count: 159

Filed under:

Say I have a sorted-set of integers, xs, and I want to retrieve all the integers in xs that are [x, y), ie. 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 elements returned to be small. Using take-while and drop-while would let me exit once I've reached y, but I still can't jump to x efficiently.

I am just learning clojure so here is how I would 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?

© Stack Overflow or respective owner

Related posts about clojure