Skip to content

Instantly share code, notes, and snippets.

@miner
Created March 14, 2018 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save miner/7462410c88147f3a47811b1f32713f69 to your computer and use it in GitHub Desktop.
Save miner/7462410c88147f3a47811b1f32713f69 to your computer and use it in GitHub Desktop.
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