Skip to content

Instantly share code, notes, and snippets.

@juergenhoetzel
Created June 1, 2010 21:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juergenhoetzel/421502 to your computer and use it in GitHub Desktop.
Save juergenhoetzel/421502 to your computer and use it in GitHub Desktop.
(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