Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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?

like image 212
Greg Rogers Avatar asked Jun 03 '10 04:06

Greg Rogers


People also ask

How do you do if else in Clojure?

In Clojure, the condition is an expression which evaluates it to be either true or false. If the condition is true, then statement#1 will be executed, else statement#2 will be executed. The general working of this statement is that first a condition is evaluated in the 'if' statement.

What is a comparator function?

A comparator is a function that takes two arguments x and y and returns a value indicating the relative order in which x and y should be sorted. It can be a 3-way comparator returning an integer, or a 2-way comparator returning a boolean.

What is a collection in Clojure?

Clojure collections "collect" values into compound values. There are four key Clojure collection types: vectors, lists, sets, and maps. Of those four collection types, vectors and lists are ordered.

What is a Clojure vector?

A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure.


1 Answers

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

(subseq xs >= x < y)
like image 171
Greg Rogers Avatar answered Sep 21 '22 11:09

Greg Rogers