Last active
November 18, 2015 19:45
-
-
Save brianfay/69aa3871d3b482539911 to your computer and use it in GitHub Desktop.
Simple implementation of comp using reduce
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
;;The one thing I don't really like about this is that I have to reverse funcs, not sure if there is a more elegant solution | |
(defn my-comp | |
[& funcs] | |
(let [funcs (reverse funcs)] | |
(fn [& args] | |
(reduce #(%2 %1) (apply (first funcs) args) (rest funcs))))) | |
;;this solution from "toolkit" on StackOverflow seems a tad better to me, but I'm not sure how it works... | |
(fn [& fs] | |
(reduce (fn [f g] | |
#(f (apply g %&))) fs)) | |
;;looks like it should expand to something like this, which is weird... maybe probably I'm misunderstanding | |
(f1 (apply f2 args)) | |
(f3 (apply (f1 (apply f2 args)) args)) | |
;;no, I was wrong, that's not quite how reduce expands - first arg is the accumulator | |
#(f1 (apply f2 args)) | |
#(#(f1 (apply f2 args)) (apply f3 args)) | |
#(#(#(f1 (apply f2 args)) (apply f3 args)) (apply f4 args)) ...etc | |
;;so ((comp str - +) [1 2 3 4 5]) becomes: | |
;;(#(str (apply - %&))(apply + [1 2 3 4 5])) | |
;;which is the same as | |
;;(str (- (+ 1 2 3 4 5))) | |
;;just uglier and way more confusing | |
;;Look how awful this is: | |
(defn reverse-str-subtract-add [a] | |
((fn [& b] | |
((fn [& c] | |
(reverse (apply str c))) | |
(apply - b)) | |
) (apply + a))) | |
(reverse-str-subtract-add [1 2 3 4 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment