Created
March 14, 2018 19:28
-
-
Save miner/7462410c88147f3a47811b1f32713f69 to your computer and use it in GitHub Desktop.
map-alt transducer
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
;; map-alt is like the map xform but calls the funtions in an alternating order | |
;; (f i0) (g i1) (h i2) (f i3) ... | |
;; | |
;; In other words, map-alt spreads fn calls across elements, whereas (mapcat (juxt ...)) calls all | |
;; fns on each element. | |
(defn map-alt | |
([] (map identity)) | |
([f] (map f)) | |
([f g] | |
(fn [rf] | |
(let [toggle (volatile! false)] | |
(fn | |
([] (rf)) | |
([result] (rf result)) | |
([result input] | |
(rf result (if (vswap! toggle not) (f input) (g input)))))))) | |
([f g & more] | |
(fn [rf] | |
(let [fv (into [f g] more) | |
cnt (count fv) | |
inc0 (fn [n] (let [n (unchecked-inc n)] (if (>= n cnt) 0 n))) | |
i (volatile! -1)] | |
(fn | |
([] (rf)) | |
([result] (rf result)) | |
([result input] | |
(rf result ((nth fv (vswap! i inc0)) input)))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment