最近我在clojure.core中看到了这段代码。
(defn sort-by
"Returns a sorted sequence of the items in coll, where the sort
order is determined by comparing (keyfn item). If no comparator is
supplied, uses compare. comparator must implement
java.util.Comparator. If coll is a Java array, it will be modified.
To avoid this, sort a copy of the array."
{:added "1.0"
:static true}
([keyfn coll]
(sort-by keyfn compare coll))
([keyfn ^java.util.Comparator comp coll]
(sort (fn [x y] (. comp (compare (keyfn x) (keyfn y)))) coll)))
参数 comp
上有一个比较器类型提示。但是 sort-by
的两个参数版本会将 clojure.core/compare
传递给它。这是如何工作的?
更新:
我想知道 clojure.core/compare
如何实现 java.util.Comparator
。 compare
看起来像这样:
(defn compare
"Comparator. Returns a negative number, zero, or a positive number
when x is logically 'less than', 'equal to', or 'greater than'
y. Same as Java x.compareTo(y) except it also works for nil, and
compares numbers and collections in a type-independent manner. x
must implement Comparable"
{
:inline (fn [x y] `(. clojure.lang.Util compare ~x ~y))
:added "1.0"}
[x y] (. clojure.lang.Util (compare x y)))
这只是一个普通的Clojure函数吗?
compare
实现了java.util.Comparator
。你是在问(a)它是如何实现的吗?(b)二元和三元定义是如何工作的?(c)类型提示有什么帮助?(d)在三元情况下,sort-by
函数本身是如何工作的?(e)还是其他什么? - JohnJ