4

Clojure 向量具有一个不常见的属性,即当您比较它们时,向量的长度会在任何其他属性之前被考虑。例如在 Haskell

Prelude> [1, 3] > [1, 2, 3]
True

和红宝石

1.9.3p392 :003 > [1, 3] <=> [1, 2, 3]
 => 1 

但是在 Clojure 中:

user=> (compare [1, 3] [1, 2, 3])
-1

现在您可以自己实现“常规”比较:

(defn vector-compare [[value1 & rest1] [value2 & rest2]]
  (let [result (compare value1 value2)]
    (cond 
      (not (= result 0)) result
      (nil? value1) 0 ; value2 will be nil as well 
      :else (recur rest1 rest2))))

但我希望这种比较向量的方式非常普遍,以至于有一种标准的方式来实现这一点。有没有?

4

2 回答 2

3

像这样的东西?

(first (filter (complement zero?) (map compare [1 3] [1 2 3])))
于 2013-03-30T11:53:42.063 回答
3

如果它们实现了接口,该compare函数会比较两件事java.lang.Comparable。Clojure 中的 Vector 实现了这个接口,如这个链接所示,基本上它首先检查长度。没有核心功能可以满足您的需求,因此您必须推出自己的功能。

Other thing I would like to mention is that the haskell version is basically comparing lists (not vector) and it is not efficient to calculate list length which make sense to avoid length while comparing lists where as vector length calculation is O(1) operation and hence it make sense to check the length first.

于 2013-03-30T12:38:49.450 回答