Skip to content

Instantly share code, notes, and snippets.

@dantheobserver
Last active June 29, 2019 02:54
Show Gist options
  • Save dantheobserver/e21b6f7fed74dca079edf2806b71791a to your computer and use it in GitHub Desktop.
Save dantheobserver/e21b6f7fed74dca079edf2806b71791a to your computer and use it in GitHub Desktop.
macro that given a sequence of values and default binding values evaluates body of form with bindings in args or defaults.
(ns with-args)
;; input
#_(with-args args
[hostname "127.0.0.1" ;; default values if args at position are not provided
port "3030"]
[hostname port])
;; output
#_(let [{hostname 0
port 1
:or {hostname "127.0.0.1"
port "3030"}} (vec args)]
[hostname port])
;; wors with argv
#_(
(defmacro with-args
"Bind a sequence of values to defaults listed in `arg-bindings` and evaluate body. "
{:style/indent [1]}
[argv arg-bindings & body]
(let [bind-list (->> (partition 2 arg-bindings)
(map-indexed (fn [i v]
[(first v) i]))
flatten)
bind-form (-> (apply hash-map bind-list)
(assoc :or (apply hash-map arg-bindings)))]
`(let [~bind-form (vec ~argv)]
~@body)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment