Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple comparator does not sort as (I) expected

Tags:

clojure

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")
like image 415
Stathis Sideris Avatar asked Apr 14 '11 15:04

Stathis Sideris


People also ask

Does Comparator sort in ascending order?

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.

What happens while sorting if the object isn't comparable?

Sorting a Set with TreeSet Again, if we use an object that is not Comparable , a ClassCastException will be thrown.

Which option is correct to sort the list using Comparator interface?

public void sort(List list, Comparator c): is used to sort the elements of List by the given Comparator.


2 Answers

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")
like image 156
Justin Kramer Avatar answered Oct 03 '22 17:10

Justin Kramer


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

like image 21
Joost Diepenmaat Avatar answered Oct 03 '22 16:10

Joost Diepenmaat