Skip to content

Instantly share code, notes, and snippets.

@nornagon nornagon/sliding.clj
Created Nov 28, 2015

Embed
What would you like to do?
(defn sliding
([^long n] (sliding n 1))
([^long n ^long step]
(fn [rf]
(let [a (java.util.ArrayDeque. n)]
(fn
([] (rf))
([result]
(let [result (if (.isEmpty a)
result
(let [v (vec (.toArray a))]
;;clear first!
(.clear a)
(unreduced (rf result v))))]
(rf result)))
([result input]
(.add a input)
(if (= n (.size a))
(let [v (vec (.toArray a))]
(dorun (take step (repeatedly #(.removeFirst a))))
(rf result v))
result)))))))
@nmashton

This comment has been minimized.

Copy link

commented Oct 22, 2016

This isn't getting us quite the same thing as partition-all, in terms of the sequences returned (and getting a transducing version of partition-all is what we want here, right?):

user=> (eduction (sliding 3 1) [1 2 3 4])
([1 2 3] [2 3 4] [3 4])
user=> (partition-all 3 1 [1 2 3 4])
((1 2 3) (2 3 4) (3 4) (4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.