Skip to content

Instantly share code, notes, and snippets.

@jotanavarro
Last active May 30, 2020 12:57
Show Gist options
  • Save jotanavarro/2b929c544f490f9dd03d616e0dc1378c to your computer and use it in GitHub Desktop.
Save jotanavarro/2b929c544f490f9dd03d616e0dc1378c to your computer and use it in GitHub Desktop.
comp
;; 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