Skip to content

Instantly share code, notes, and snippets.

@hung-phan
Created May 2, 2015 14:37
Show Gist options
  • Select an option

  • Save hung-phan/782e3d1303069f0d8a56 to your computer and use it in GitHub Desktop.

Select an option

Save hung-phan/782e3d1303069f0d8a56 to your computer and use it in GitHub Desktop.
Usefull macros for clojure
(defn collect-bodies [forms]
(for [form (partition 3 forms)]
(build-contract form)))
(defn build-contract [c]
(let [args (first c)]
(list
(into '[f] args)
(apply merge (for [con (rest c)]
(cond
(= (first con) 'require) (assoc {} :pre (vec (rest con)))
(= (first con) 'ensure) (assoc {} :post (vec (rest con)))
:else (throw (Exception. (str "Unknown tag " (first con)))))))
(list* 'f args))))
(defmacro contract [name & forms]
(list* `fn name (collect-bodies forms)))
;; How to use
(def double-contract
(contract doubler
[x]
(require (pos? x))
(ensure (= (* 2 x) %)))
(def times2 (partial doubler-contract #(* 2 x)))
(times2 9) ;; => 18
@hung-phan
Copy link
Copy Markdown
Author

From The Joy of Clojure second edition

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