Last active
March 1, 2017 21:30
-
-
Save favila/db6c9d5a5b56fefbc505d8e18a38873c to your computer and use it in GitHub Desktop.
partition-key-by: Clojure transducer which emits the value of `(f x)` every time it changes. Useful when you want to use distinct on a collection you know is already sorted, or group-by but only care about the keys.
This file contains hidden or 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
(defn partition-key-by | |
"Return a transducer which emits the value of `(f x)` every time it changes. | |
This is the same as the following, except far more efficient because it will | |
not retain large intermediate collections: | |
(comp | |
(map f) | |
(partition-all) | |
(map first)) | |
This function is chiefly useful with sorted collections." | |
[f] | |
(fn [xf] | |
(let [last (volatile! (Object.))] | |
(fn | |
([] (xf)) | |
([r] (vreset! last nil) (xf r)) | |
([r x] | |
(let [k (f x)] | |
(if (= k @last) | |
r | |
(do | |
(vreset! last k) | |
(xf r k))))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment