Created
November 8, 2015 03:58
-
-
Save brianfay/767ffbecda2743f2cfa4 to your computer and use it in GitHub Desktop.
Implement map using reduce (clojure)
This file contains hidden or 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
;;Excerpt "Clojure for the Brave and True" by Daniel Higginbotham: | |
;;"If you want an exercise that will really blow your hair back, try implementing map using reduce..." | |
;;This actually took me a really long time to come up with, have to keep thinking about how reduce expands to (fn (fn (fn... | |
;;Tried cons first, but couldn't figure it out - needed to think about the order arguments are applied in within the anonymous | |
;;function AND the order of arguments for reduce. That was more obvious after I tried using conj | |
(defn my-map-conj | |
"map implemented in terms of reduce and conj" | |
[f coll] | |
(reduce #(conj %1 (f %2)) [] coll)) | |
(defn my-map-cons | |
"map implemented in terms of reduce and cons" | |
[f sequence] | |
(reduce #(cons (f %2) %1) '() (reverse sequence))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The thing is,
map
takes many collections as arguments, not just a single one :).