Is there a standard way to compare Clojure vectors in the "normal" way

Clojure vectors have an unusual property that when comparing their length, the vector is considered before any other property. In particular. Haskell

Prelude> [1, 3] > [1, 2, 3] True 

and Ruby

 1.9.3p392 :003 > [1, 3] <=> [1, 2, 3] => 1 

But in Clojure:

 user=> (compare [1, 3] [1, 2, 3]) -1 

Now you can implement the β€œnormal” comparison yourself:

 (defn vector-compare [[value1 & rest1] [value2 & rest2]] (let [result (compare value1 value2)] (cond (not (= result 0)) result (nil? value1) 0 ; value2 will be nil as well :else (recur rest1 rest2)))) 

but I expect that this way of comparing vectors is so common that there is a standard way to achieve this. There is?

+4
source share
2 answers

The compare function compares 2 things if they implement the java.lang.Comparable interface. A vector in Clojure implements this interface, as shown on this link, basically it checks the length first. There is no main function that does what you want, so you have to minimize your own function.

Another thing that I would like to mention is that the haskell version mainly compares lists (not the vector), and it is inefficient to calculate the length of the list, which makes sense to avoid length when comparing lists, where when calculating the length of the vector is O (1), and therefore it makes sense to check the length first.

+3
source

Something like that?

 (first (filter (complement zero?) (map compare [1 3] [1 2 3]))) 
+3
source

All Articles