Simple comparator does not sort as (I) expected

I was expecting this piece of code to create the original vector, but sorted case-insensitively. Instead, I get the original vector intact. Why is my comparator not working?

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") 
+4
source share
2 answers

comparator returns a java.util.Comparator when specifying a predicate (a function that returns true or false). You do not need this if you use explicitly compare . So simple:

 (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") 
+14
source

Comparison is not a predicate; it is a comparator.

+1
source

Source: https://habr.com/ru/post/1348125/


All Articles