如何检查当前值是否大于 Clojure 中的下一个值?
How to check if current value is greater than the next value in Clojure?
我正在寻找一种方法来检查集合中的当前值是否大于下一个值,如果是,则将那对项目添加到集合中,例如:
[9 2 3 7 11 8 3 7 1] => [9 2 11 8 8 3 7 1] ; Checking each item against the next
我最初认为我可以做类似的事情:
(filter (fn [[x y]] (> x y)) [9 2 3 7 11 8 3 7 1])
但是类似这样的东西似乎只适用于关联类型。然后我尝试了这样的事情:
(defn get-next [col index] ; Returns next item from a collection
(get col (inc (.indexOf col index))))
(filter (fn [[x]] (> x (get-next [9 2 3 7 11 8 3 7 1] x))) [9 2 3 7 11 8 3 7 1])
但我仍然遇到同样的错误。任何帮助将不胜感激
使用 partition
函数在 collection.
中生成当前项和下一项
user=> (partition 2 1 [9 2 3 7 11 8 3 7 1])
((9 2) (2 3) (3 7) (7 11) (11 8) (8 3) (3 7) (7 1))
现在您在 collection 中有一对当前项目和下一个项目。您可以比较每对中的项目并将结果与 mapcat
.
连接
user=> (->> [9 2 3 7 11 8 3 7 1]
#_=> (partition 2 1)
#_=> (mapcat (fn [[a b]] (if (> a b) [a b]))))
(9 2 11 8 8 3 7 1)
另一种方法是使用 reduce
:
(defn pairs [data]
((reduce (fn [res item]
(if (and (:prev res) (< item (:prev res)))
(assoc res
:prev item
:res (conj (:res res) (:prev res) item))
(assoc res :prev item)))
{:prev nil :res []} data) :res))
(pairs [9 2 3 7 11 8 3 7 1])
;; [9 2 11 8 8 3 7 1]
我正在寻找一种方法来检查集合中的当前值是否大于下一个值,如果是,则将那对项目添加到集合中,例如:
[9 2 3 7 11 8 3 7 1] => [9 2 11 8 8 3 7 1] ; Checking each item against the next
我最初认为我可以做类似的事情:
(filter (fn [[x y]] (> x y)) [9 2 3 7 11 8 3 7 1])
但是类似这样的东西似乎只适用于关联类型。然后我尝试了这样的事情:
(defn get-next [col index] ; Returns next item from a collection
(get col (inc (.indexOf col index))))
(filter (fn [[x]] (> x (get-next [9 2 3 7 11 8 3 7 1] x))) [9 2 3 7 11 8 3 7 1])
但我仍然遇到同样的错误。任何帮助将不胜感激
使用 partition
函数在 collection.
user=> (partition 2 1 [9 2 3 7 11 8 3 7 1])
((9 2) (2 3) (3 7) (7 11) (11 8) (8 3) (3 7) (7 1))
现在您在 collection 中有一对当前项目和下一个项目。您可以比较每对中的项目并将结果与 mapcat
.
user=> (->> [9 2 3 7 11 8 3 7 1]
#_=> (partition 2 1)
#_=> (mapcat (fn [[a b]] (if (> a b) [a b]))))
(9 2 11 8 8 3 7 1)
另一种方法是使用 reduce
:
(defn pairs [data]
((reduce (fn [res item]
(if (and (:prev res) (< item (:prev res)))
(assoc res
:prev item
:res (conj (:res res) (:prev res) item))
(assoc res :prev item)))
{:prev nil :res []} data) :res))
(pairs [9 2 3 7 11 8 3 7 1])
;; [9 2 11 8 8 3 7 1]