Last active
May 10, 2017 17:50
-
-
Save bostonaholic/4fd7a56731410082f2908a0ed4f8fcdc to your computer and use it in GitHub Desktop.
Transducers in a nut-shell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; 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