开发者

Simple comparator does not sort as (I) expected

开发者 https://www.devze.com 2023-02-25 01:38 出处:网络
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?

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消