Skip to content

Instantly share code, notes, and snippets.

@trevorc
Created March 23, 2012 19:24
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 trevorc/2174086 to your computer and use it in GitHub Desktop.
Save trevorc/2174086 to your computer and use it in GitHub Desktop.
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