Skip to content

Instantly share code, notes, and snippets.

@bostonaholic
Last active May 10, 2017 17:50
Show Gist options
  • Save bostonaholic/4fd7a56731410082f2908a0ed4f8fcdc to your computer and use it in GitHub Desktop.
Save bostonaholic/4fd7a56731410082f2908a0ed4f8fcdc to your computer and use it in GitHub Desktop.
Transducers in a nut-shell
;; From tbaldridge on Slack
(defn map [f coll]
(reduce (fn [acc i]
(conj acc (f i)))
[]
coll))
(map inc [1 2 3]) ;;=> [2 3 4]
;; refactor to pull out reduce
(defn mapping [f]
(fn [acc i]
(conj acc (f i)))
(reduce (mapping inc) [] [1 2 3]) ;;=> [2 3 4]
;; But this isn't good enough because our accumulator may not support `conj`
;; Refactor once more:
(defn mapping [f]
(fn [xf]
(fn [acc i]
(xf acc (f i)))))
(reduce ((mapping inc) conj) [] [1 2 3]) ;;=> [2 3 4]
(reduce ((mapping inc) +) 0 [1 2 3]) ;;=> 9
;; Now you can reuse `mapping` in a dozen different situations and we never have to define a mapping transducer again.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment