I have a compare function which I use as the first argument of
sort. I have occasionally gotten an exception raised by Tim Sort that my compare function does not enforce certain invariants. However, the error message does not report the offending input sequence being sorted.
My attempts to print the sequence before sorting it have failed, as the exception is rare. I tried refactoring my compare function, guessing about what the error might be. I cannot reproduce error.
Can someone take a look at my function and warn me about potential problems?
(defn sort-operands [operands] (letfn [(cmp [a b] (cond (= a b) 0 (not (= (type a) (type b))) (compare (.getName (type a)) (.getName (type b))) (and (seq? a) (seq? b)) (loop [a a b b] (cond (and (empty? a) (empty? b)) 0 ;; can this occur? we know the sequences are not = (empty? a) 1 (empty? b) -1 (= (first a) (first b)) (recur (rest a) (rest b)) :else (cmp (first a) (first b)))) (seq? a) 1 ;; can this occur? because (type a) = (type b), and they are not both seq? (seq? b) -1 :else (compare a b)))] (sort cmp operands)))