-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patha-d-d-step2.clj
29 lines (28 loc) · 866 Bytes
/
a-d-d-step2.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
; From https://github.com/clojure/clojure/blob/clojure-1.9.0/src/clj/clojure/core.clj#L7532
(defn preserving-reduced [rf]
(fn [a b]
(let [ret (rf a b)]
(if (reduced? ret)
(reduced ret)
ret))))
; Step 2
(defn a-d-d [n]
(fn [rf]
(let [rrf (preserving-reduced rf)]
(let [state (volatile! [])]
(fn ([] (rf))
([result]
(let [buffer @state]
(-> (if (seq buffer)
(reduce rrf result buffer)
result)
(rf))))
([result input]
(let [buffer (conj @state input)]
(if (>= (count buffer) n)
(do
(vreset! state [])
(reduce rrf result buffer))
(do
(vreset! state buffer)
result)))))))))