Skip to content

Instantly share code, notes, and snippets.

@Bclayson
Last active April 23, 2016 18:17
Show Gist options
  • Save Bclayson/5d5f1c2ff537240a964c0cac34e784ff to your computer and use it in GitHub Desktop.
Save Bclayson/5d5f1c2ff537240a964c0cac34e784ff to your computer and use it in GitHub Desktop.
Make your Clojure functions auto-cury
; This function decorator returns an auto currying version of the function passed to it
; a helper function that looks at a functions metadata to get the number of arguments required
(defn arities
[v]
(-> v meta :arglists first count))
; curry takes a function quote (ex. #'map) and any initial arguments you may want to pass to it (or none) and if all the arguments aren't
; fulfilled it returns a curry. You can continue to call each curry and it will return another one until all args are fulfilled
(defn curry
[func-quote & initial-args]
(fn
[& rest-args]
(let [current-args (or initial-args '())
total-args (flatten (concat current-args rest-args))]
(if (= (count total-args) (arities func-quote))
(apply func-quote total-args)
(curry func-quote total-args)
))))
(defn adder
[a b c d e]
(+ a b c d e))
(def add-five (curry #'adder 5))
; returns a curry with argument 'a' defined as 5
(def add-fifteen (add-five 5 5))
; Now 'a', 'b', and 'c' are defined as 5.
(add-fifteen 15 15)
; => 45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment