我正在寻找一种方法来检查集合中的当前值是否大于下一个值,如果是,则将该对项添加到集合中,例如:
[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])
但我仍然遇到同样的错误。任何帮助将不胜感激
答案 0 :(得分:2)
使用partition
函数在集合中创建当前和下一项对。
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))
现在你在集合中有一对当前和下一个项目。您可以比较每对中的项目,并将结果与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)
答案 1 :(得分:0)
另一种方法是使用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]