Created
March 3, 2021 14:53
-
-
Save damesek/00e8369e14beb7e4a14d9aef6ff74d0a to your computer and use it in GitHub Desktop.
Partition-by re-implementation
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
; Partition by "identity" | |
(def sdta [1 1 2 2 3 3 2 3 4 4]) | |
(if (= (last (flatten sdata)) 3) | |
(conj (pop sdata) (conj (peek sdata) 4)) | |
(conj sdata [3])) | |
(defn -partition-by [] | |
(fn [acc v] | |
(if (= (last (flatten acc)) v) | |
(conj (pop acc) (conj (peek acc) v)) | |
(conj acc [v])))) | |
(reduce (-partition-by) | |
[] | |
sdta) | |
;=> [[1 1] [2 2] [3 3] [2] [3] [4 4]] | |
(reduce (-partition-by) | |
[] | |
(vec "hello world")) | |
;=> [[\h] [\e] [\l \l] [\o] [\space] [\w] [\o] [\r] [\l] [\d]] | |
(defn -partition-by [f] | |
(fn [acc v] | |
(letfn [(logic [f acc v] | |
(if-not (empty? acc) | |
(if (= (f (last (flatten acc))) (f v)) | |
(conj (pop acc) (conj (peek acc) v)) | |
(conj acc [v])) | |
(conj acc [v])))] | |
(logic f acc v) | |
))) | |
(reduce (-partition-by odd?) | |
[] | |
sdta) | |
;=> [[1 1] [2 2] [3 3] [2] [3] [4 4]] | |
(def sdta [1 1 1 5 2 2 3 3 2 3 4 4]) | |
(reduce (-partition-by odd?) | |
[] | |
sdta) | |
;=> [[1 1 1 5] [2 2] [3 3] [2] [3] [4 4]] | |
(reduce (-partition-by identity) | |
[] | |
sdta) | |
;=> [[1 1 1] [5] [2 2] [3 3] [2] [3] [4 4]] | |
; [pre-transducer] | |
(defn -rpartition-by [f] | |
(fn [xf] | |
(fn [acc v] | |
(letfn [(logic [xf acc v] | |
(if-not (empty? acc) | |
(if (= (xf (last (flatten acc))) (xf v)) | |
(conj (pop acc) (conj (peek acc) v)) | |
(conj acc [v])) | |
(conj acc [v])))] | |
(logic xf acc v) | |
)))) | |
(defn -mapping [f] | |
(fn [xf] | |
(fn [acc v] | |
(xf acc (f v))))) | |
(def rfn (comp (-mapping inc) | |
(-rpartition-by odd?))) | |
(reduce (rfn conj) | |
[] | |
sdta) | |
;=> [[2 2 2] [6] [3 3] [4 4] [3] [4] [5 5]] | |
; transducer | |
(defn -transduce-partition-by [f] | |
(fn [xf] | |
(fn | |
([] (xf)) | |
([acc] (xf acc)) | |
([acc v] | |
(letfn [(logic [xf acc v] | |
(if-not (empty? acc) | |
(if (= (xf (last (flatten acc))) (xf v)) | |
(conj (pop acc) (conj (peek acc) v)) | |
(conj acc [v])) | |
(conj acc [v])))] | |
(logic xf acc v) | |
))))) | |
(transduce (-transduce-partition-by odd?) conj sdta) | |
;=> [[1 1 1] [5] [2 2] [3 3] [2] [3] [4 4]] | |
(transduce (comp (map inc) (-transduce-partition-by odd?)) conj sdta) | |
;=> [[2 2 2] [6] [3 3] [4 4] [3] [4] [5 5]] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment