Skip to content

Instantly share code, notes, and snippets.

@nikolavojicic
Last active December 13, 2024 13:12
Show Gist options
  • Save nikolavojicic/9e3e2006cb6fb315749bf5f6c7d394bd to your computer and use it in GitHub Desktop.
Save nikolavojicic/9e3e2006cb6fb315749bf5f6c7d394bd to your computer and use it in GitHub Desktop.
Introduction to Transducers (https://www.youtube.com/watch?v=WkHdqg_DBBs)
(defn -map [f coll] ;; coll :(
(reduce
(fn [res elt]
(conj res (f elt))) ;; conj :(
[] coll))
(-map inc (range 10))
(defn -filter [f coll] ;; coll :(
(reduce
(fn [res elt]
(if (f elt)
(conj res elt) ;; conj :(
res))
[] coll))
(-filter odd? (range 10))
(defn -mapping [f] ;; no coll :)
(fn [res elt]
(conj res (f elt)))) ;; conj :(
((-mapping inc) [] 1)
(reduce (-mapping inc) [] (range 10))
(defn -mapping' [f f-acc] ;; f-acc :(
(fn [res elt]
(f-acc res (f elt)))) ;; no conj :)
((-mapping' inc conj) [] 1)
(reduce (-mapping' inc conj) [] (range 10))
(defn -mapping'' [f] ;; no f-acc :)
(fn [f-acc]
(fn [res elt]
(f-acc res (f elt)))))
(((-mapping'' inc) conj) [] 1)
(reduce ((-mapping'' inc) conj) [] (range 10))
(defn -filtering'' [f]
(fn [f-acc]
(fn [res elt]
(if (f elt)
(f-acc res elt)
res))))
(def xf ;; fully reusable
(comp ;; note: comp order
(-mapping'' inc) ;; (map inc)
(-filtering'' odd?))) ;; (filter odd?)
(reduce (xf conj) [] (range 10))
(reduce (xf +) 0 (range 10))
(reduce ((comp (map inc) (filter odd?)) +) (range 10)) ;; 24 <- read the docs, see reductions
(transduce (comp (map inc) (filter odd?)) + (range 10)) ;; 25
(reduce ((comp (map inc) (filter odd?)) +) 0 (range 10)) ;; 25
;; monoid: (+) => 0, (*) => 1 etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment