Created
May 2, 2015 14:37
-
-
Save hung-phan/782e3d1303069f0d8a56 to your computer and use it in GitHub Desktop.
Usefull macros for clojure
This file contains 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
(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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From
The Joy of Clojure
second edition