Created
June 1, 2010 21:11
-
-
Save juergenhoetzel/421502 to your computer and use it in GitHub Desktop.
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
(defmacro defcontract [name & forms] | |
(let [body (collect-bodies forms)] | |
(list* 'defn name body))) | |
(declare build-contract) | |
(defn collect-bodies [forms] | |
(for [form (partition 3 forms)] | |
(build-contract form))) | |
(defn build-contract [[args & cs]] | |
(list | |
(into '[f] args) | |
(apply merge | |
(for [[tag & conds] cs] | |
(case tag | |
require {:pre (vec conds)} | |
ensure {:post (vec conds)} | |
(throw (Exception. (str "Unknown tag " tag)))))) | |
(list* 'f args))) | |
(defcontract doubler-contract | |
[x] | |
(require | |
(pos? x)) | |
(ensure | |
(= (* 2 x) %)) | |
[x y] | |
(require | |
(pos? x) (pos? y)) | |
(ensure | |
(= (* 2 (+ x y)) %))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment