Skip to content

Instantly share code, notes, and snippets.

@nornagon
Created November 28, 2015 19:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nornagon/03b85fbc22b3613087f6 to your computer and use it in GitHub Desktop.
Save nornagon/03b85fbc22b3613087f6 to your computer and use it in GitHub Desktop.
(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
Copy link

nmashton 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