Skip to content

Instantly share code, notes, and snippets.

@miner miner/map-alt.clj
Created Mar 14, 2018

Embed
What would you like to do?
map-alt transducer
;; 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
You can’t perform that action at this time.