tags:

views:

51

answers:

1

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?

+4  A: 

Oops! I missed the subseq function, there is no link to it from the data structures page of the documentation.

(subseq xs >= x < y)
Greg Rogers