Skip to content

Instantly share code, notes, and snippets.

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

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]
(empty? ~bindings-sym) `(do ~@~body-sym)
(symbol? (~bindings-sym 0))
`(let ~(subvec ~bindings-sym 0 2)
(~'~name ~(subvec ~bindings-sym 2) ~@~body-sym)
(~~finalizer ~(~bindings-sym 0)))))))))
;; for example:
(defwith with-delete
(fn [x] (. x delete)))
(with-delete [tmp ( "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.