Skip to content

Instantly share code, notes, and snippets.

@trevorc trevorc/defwith.clj
Created Mar 23, 2012

Embed
What would you like to do?
defwith -- sugar for try-finally macros
(defmacro defwith [name finalizer]
(let [bindings-sym (gensym "bindings")
body-sym (gensym "body")]
`(defmacro ~name [~bindings-sym & ~body-sym]
(cond
(empty? ~bindings-sym) `(do ~@~body-sym)
(symbol? (~bindings-sym 0))
`(let ~(subvec ~bindings-sym 0 2)
(try
(~'~name ~(subvec ~bindings-sym 2) ~@~body-sym)
(finally
(~~finalizer ~(~bindings-sym 0)))))))))
(comment
;; for example:
(defwith with-delete
(fn [x] (. x delete)))
(with-delete [tmp (java.io.File/createTempFile "tmp" nil)]
(println "temporary file: " tmp))
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.