我正在努力寻找一种美观、惯用的方式来编写函数
(defn remove-smaller
[coll partial-order-fn]
___
)
其中 partial-order-fn
接受两个参数,如果它们具有可比性(分别较小、等于、较大),则返回 -1 0 或 1,否则返回 nil
。
remove-smaller
的结果应该是 coll,所有小于 coll 中任何其他项目的项目都将被删除。
示例:如果我们定义了一个偏序,例如数字可以正常比较,字母也可以比较,但字母和数字不可以比较:
1 < 2 a < t 2 ? a
然后我们就会:
(remove-smaller [1 9 a f 3 4 z])
==> [9 z]
最佳答案
(defn partial-compare [x y]
(when (= (type x) (type y))
(compare x y)))
(defn remove-smaller [coll partial-order-fn]
(filter
(fn [x] (every? #(let [p (partial-order-fn x %)]
(or (nil? p) (>= p 0)))
coll))
coll))
(defn -main []
(remove-smaller [1 9 \a \f 3 4 \z] partial-compare))
这会输出 (9\z)
,这是正确的,除非您希望返回值与 coll
具有相同的类型。
关于clojure - 给定一个部分有序的集合,删除所有较小的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15581690/