I expected this code snippet to produce the original vector, but sorted in a case-insensitive way. Instead I get the original vector untouched. Why doesn't my comparator work?
user=> (ns user (require [clojure.contrib.string :as str]))
nil
user=> (sort
(comparator #(compare (str/upper-case %1) (str/upper-case %2)))
["B" "a" "c" "F" "r" "E"])
("B" "a" "c" "F" "r" "E")
In java, a Comparator is provided in java. Override the compare() method in such a way that it will reorder an ArrayList in descending order instead of ascending order.
Sorting a Set with TreeSet Again, if we use an object that is not Comparable , a ClassCastException will be thrown.
public void sort(List list, Comparator c): is used to sort the elements of List by the given Comparator.
comparator
returns a java.util.Comparator
when given a predicate (a function which returns true or false). You don't need it if you're using compare
explicitly. So just:
(sort #(compare (str/upper-case %1) (str/upper-case %2))
["B" "a" "c" "F" "r" "E"])
;=> ("a" "B" "c" "E" "F" "r")
Alternatively, use sort-by
:
(sort-by str/upper-case ["B" "a" "c" "F" "r" "E"])
;=> ("a" "B" "c" "E" "F" "r")
compare is not a predicate, it's a comparator.
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