Last active
May 30, 2020 12:57
-
-
Save jotanavarro/2b929c544f490f9dd03d616e0dc1378c to your computer and use it in GitHub Desktop.
comp
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
;; The clojure comp cre function | |
;; Recursive | |
(defn my-comp | |
([] my-comp) | |
([f] f) | |
([f & fs] | |
(fn [& args] | |
(f (apply (apply my-comp fs) args))))) | |
;; Tail-recursive-esque, using loop and recur | |
(defn better-comp | |
([] identity) | |
([& fns] | |
(fn [& args] | |
(let [sorted-fns (reverse fns) | |
first-f (apply (first sorted-fns) args)] | |
(loop [initial-fn first-f | |
remaining-fns (rest sorted-fns)] | |
(if (empty? remaining-fns) | |
initial-fn | |
(let [future-fn (first remaining-fns) | |
remaining-fns (rest remaining-fns)] | |
(recur (future-fn initial-fn) remaining-fns)))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment