Skip to content

Instantly share code, notes, and snippets.

@brianfay
Created November 8, 2015 03:58
Show Gist options
  • Save brianfay/767ffbecda2743f2cfa4 to your computer and use it in GitHub Desktop.
Save brianfay/767ffbecda2743f2cfa4 to your computer and use it in GitHub Desktop.
Implement map using reduce (clojure)
;;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)))
@VadimPushtaev
Copy link

The thing is, map takes many collections as arguments, not just a single one :).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment