Skip to content

Instantly share code, notes, and snippets.

@alandipert
Last active March 18, 2016 18:26
Show Gist options
  • Select an option

  • Save alandipert/11640ac9286a254eb837 to your computer and use it in GitHub Desktop.

Select an option

Save alandipert/11640ac9286a254eb837 to your computer and use it in GitHub Desktop.
inline pre/post conditions macro
(defmacro with-conditions
[conditions & body]
{:pre [(map? conditions)]}
(if-not *assert*
`(do ~@body)
(let [ret (gensym "ret")]
`(do ~@(for [pre (:pre conditions)]
`(when-not ~pre
(throw (ex-info "Precondition failed" {:pre '~pre}))))
(let [~ret (do ~@body)]
~@(for [post (:post conditions)]
`(when-not (let [~'% ~ret] ~post)
(throw (ex-info "Postcondition failed" {:post '~post}))))
~ret)))))
(defn foop [x y]
(with-conditions
{:pre [(even? x)] :post [(odd? %)]}
(+ x y)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment