Stathis Sideris
Stathis Sideris

Reputation: 624

Simple comparator does not sort as (I) expected

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")

Upvotes: 7

Views: 1914

Answers (2)

Joost Diepenmaat
Joost Diepenmaat

Reputation: 17771

compare is not a predicate, it's a comparator.

Upvotes: 1

Justin Kramer
Justin Kramer

Reputation: 4003

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")

Upvotes: 17

Related Questions