Last active
April 23, 2016 18:17
-
-
Save Bclayson/5d5f1c2ff537240a964c0cac34e784ff to your computer and use it in GitHub Desktop.
Make your Clojure functions auto-cury
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
; 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