Skip to content

Instantly share code, notes, and snippets.

@robertpfeiffer
Created January 27, 2009 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertpfeiffer/53325 to your computer and use it in GitHub Desktop.
Save robertpfeiffer/53325 to your computer and use it in GitHub Desktop.
(defn comp
"Takes a set of functions and returns a fn that is the composition
of those fns. The returned fn takes a variable number of args,
applies the rightmost of fns to the args, the next
fn (right-to-left) to the result, etc."
([] identity)
([fun] fun)
([& fs]
(let [fs (reverse fs)]
(fn [& args]
(loop [ret (apply (first fs) args) fs (rest fs)]
(if fs
(recur ((first fs) ret) (rest fs))
ret))))))
(defmacro ->
"Threads the expr through the forms. Inserts x as the
second item in the first form, making a list of it if it is not a
list already. If there are more forms, inserts the first form as the
second item in second form, etc."
([x] x)
([x form] (if (seq? form)
`(~(first form) ~x ~@(rest form))
(list form x)))
([x form & more] `(-> (-> ~x ~form) ~@more)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment