Welcome! Please see the About page for a little more info on how this works.

0 votes
in Errors by
retagged by

Hi, when I try to compare certain vectors, I get the above-mentioned error message. I tried in Clojure 1.10.3 and babashka v1.0.168.
These are some of the offending vectors:

(compare [[1] [2 3 4]], [[1] 4])
 ;=> Execution error (ClassCastException) at user/eval1 (REPL:1). 
 ;class java.lang.Long cannot be cast to class clojure.lang.IPersistentVector (java.lang.Long is in module java.base of loader 'bootstrap'; clojure.lang.IPersistentVector is in unnamed module of loader 'app')

(compare [[[1 4 []] [6 2] 6 7 6] [[[10 4]] [10] [[3 5 1 9] 3 1 [7 5] 8] 2] [1 [2 [0 3] [2 10 2] 2] [[2 9 7 8 0] [6 0] 10] 9] [[[8 5 8 3]] 2 [2 3 [7 8]]] [0]]
         [[[[3] 4 4] 10 5 2 []] [7 8] [7 7 [[]]] [] [[[4 10 6 7]] [9] [] 3]])

Is this a bug, or am I just blind as to why this is obviously expected behavior?

I came across this while doing one of the Advent of Code programming exercises yesterday. It asks you to compare a number of vectors, see https://adventofcode.com/2022/day/13

I did solve the exercise by implementing my own vector comparator, according to the specifications given in the exercise. I uploaded the source code in case you want it for testing purposes: https://github.com/eNotchy/Advent-of-Code-2022/tree/main/Day13

1 Answer

+1 vote
by
selected by
 
Best answer

Comparing vectors will compare the elements in each index. For the example you have, the second elements are a number and a vector. The default comparator (which is the compare function) is not a universal comparator - there is no defined comparison between a number and a vector. So you will get a ClassCastException trying to compare them.

You can use functions like sort or sort-by that also take a custom comparator. More on comparators here: https://clojure.org/guides/comparators

by
Thank you, that answers my question.

Anyone who finds this thread via a search engine may feel free to use the custom comparator for more heterogeneous vectors which I wrote, although they may want to modify it to work with other primitive types than just Longs:
https://github.com/eNotchy/Advent-of-Code-2022/blob/main/Day13/2.clj
...