Last active
February 25, 2016 02:09
-
-
Save akbiggs/86f5bd96b7303b5c3882 to your computer and use it in GitHub Desktop.
A convenient macro for creating a function with default values for arguments.
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
(defmacro defn-defaults [name args body] | |
"Create a function that can provide default values for arguments. | |
Arguments that are optional should be placed in a hash as the | |
last argument with their names mapped to their default values. | |
When invoking the function, :<optional-argument-name> <value> | |
specifies the value the argument should take on." | |
(if (map? (last args)) | |
`(defn | |
~name | |
~(let [mandatory-args (drop-last args) | |
options (last args) | |
option-names (vec (keys options))] | |
(vec (concat mandatory-args | |
[(symbol "&") {:keys option-names | |
:or options}]))) | |
~@body) | |
`(defn ~name ~args ~@body))) | |
; EXAMPLE | |
(defn-defaults foo [a b {c 5 d 10}] | |
(+ a b c d)) | |
(foo 5 10) ;=> 30 | |
(foo 5 10 :c 10 :d 20) ;=> 45 | |
(foo 5 10 :c 0) ;=> 25 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi. First line should be
(defmacro defn-defaults [name args & body]