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?
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.
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.
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.
A Vector is a collection of values indexed by contiguous integers. A vector is created by using the vector method in Clojure.
Oops! I missed the subseq function, there is no link to it from the data structures page of the documentation.
(subseq xs >= x < y)
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