Skip to content

Instantly share code, notes, and snippets.

@akbiggs
Last active February 25, 2016 02:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akbiggs/86f5bd96b7303b5c3882 to your computer and use it in GitHub Desktop.
Save akbiggs/86f5bd96b7303b5c3882 to your computer and use it in GitHub Desktop.
A convenient macro for creating a function with default values for arguments.
(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
@NeedMoreDesu
Copy link

Hi. First line should be
(defmacro defn-defaults [name args & body]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment