Skip to content

Instantly share code, notes, and snippets.

@henryw374
Created March 9, 2019 07:53
Show Gist options
  • Save henryw374/5a70a8050edbfa25a189d13eb72ce712 to your computer and use it in GitHub Desktop.
Save henryw374/5a70a8050edbfa25a189d13eb72ce712 to your computer and use it in GitHub Desktop.
(ns transducers)
;;;;; simplified traditional impls
(defn mymap [f coll]
(reduce
(fn [acc n]
(conj acc (f n)))
[]
coll))
(defn myfilter [f coll]
(reduce
(fn [acc n]
(if (f n)
(conj acc n)
acc))
[]
coll))
(mymap inc [1 2 3 4 5])
(myfilter odd? [1 2 3 4 5])
;;;;;;;;;;;;;;;; transducer versions
(defn mapx [f]
(fn [process]
(completing (fn [acc n]
(process acc (f n))))))
(defn filterx [f]
(fn [process]
(completing (fn [acc n]
(if (f n)
(process acc n)
acc)))))
(reduce
((comp
(mapx inc)
(filterx odd?))
conj)
#{} [2 3 4 5 6])
;needed to add 'completing' to xf so last step of transduce works
; (conj) returns [], the output coll
(transduce
(comp
(mapx inc)
(filterx odd?))
conj [2 3 4 5 6])
; provide the output coll. clojure uses conj under the hood
(into #{} (comp
(mapx inc)
(filterx odd?)) [2 3 4 5 6])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment