在Clojure中,如何以最好的方式在(有限且不太大的)序列上使用滑动窗口?我应该只使用
drop
和take
并跟踪当前索引,还是我错过了更好的方法?drop
和take
并跟踪当前索引,还是我错过了更好的方法?我认为使用步长为1的partition函数即可实现:
user=> (partition 3 1 [3 1 4 1 5 9])
((3 1 4) (1 4 1) (4 1 5) (1 5 9))
user=> (def a [3 1 4 1 5 9])
user=> (map (partial apply +) (partition 3 1 a))
(8 6 10 15)
user=> (map + a (next a) (nnext a))
(8 6 10 15)
我不知道 partition
可以这样做,所以我就用了这种方式实现它。
(defn sliding-window [seq length]
(loop [result ()
remaining seq]
(let [chunk (take length remaining)]
(if (< (count chunk) length)
(reverse result)
(recur (cons chunk result) (rest remaining))))))