Created
February 20, 2023 17:19
-
-
Save matthewdowney/838b78636fbf9e3ace349a458a9ba2aa to your computer and use it in GitHub Desktop.
Transducers, but with state stored inside the "result" instead of in atoms / volatiles.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;; Transducers, but with state stored inside the "result" instead of in atoms | |
;;; / volatiles. | |
(defn map1 [f] | |
(fn [[rf idx]] | |
[(fn | |
([] (rf)) | |
([result] (rf result)) | |
([result input] (rf result (f input)))) | |
(inc idx)])) | |
(defn partition1 [n] | |
(fn [[rf idx]] | |
[(fn | |
([] (rf)) | |
([result] | |
(let [window (get-in result [idx :window]) | |
result (if (seq window) | |
(rf (update result idx dissoc :window) window) | |
result)] | |
(rf result))) | |
([result input] | |
(let [window (conj (get-in result [idx :window] []) input)] | |
(if (= (count window) n) | |
(-> result | |
(assoc-in [idx :window] []) | |
(rf window)) | |
(assoc-in result [idx :window] window))))) | |
(inc idx)])) | |
(let [[rf _] | |
((comp (map1 inc) (partition1 3)) | |
[(fn | |
([xs x] (update xs :result conj x)) | |
([xs] xs)) | |
0])] | |
(transduce identity rf {:result []} (range 10))) | |
;=> {:result [[1 2 3] [4 5 6] [7 8 9] [10]], 0 {}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment