Skip to content

Instantly share code, notes, and snippets.

@rplevy
Created June 29, 2012 23:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rplevy/3021378 to your computer and use it in GitHub Desktop.
Save rplevy/3021378 to your computer and use it in GitHub Desktop.
with and within
(defmacro with
"do things with the first expression passed,
and produce the result"
[expr & body]
`(let [~'% ~expr] ~@body))
(defmacro within
"do things with the first expression passed (for side effects),
but produce the value of the first expression"
[expr & body]
`(let [~'% ~expr] ~@body ~'%))
;;----
(facts
"with and within"
(with (+ 1 2 3) (println "x") (println %) (println "y"))
=> nil
(within (+ 1 2 3) (println "x") (println %) (println "y"))
=> 6
(with (+ 1 2 3) (println "x") (println %) (println "y") (inc %))
=> 7
(within (+ 1 2 3) (println "x") (println %) (println "y") (inc %))
=> 6
(with-out-str
(with (+ 1 2 3) (println "x") (println %) (println "y") (inc %)))
=> "x\n6\ny\n"
(with-out-str
(within (+ 1 2 3) (println "x") (println %) (println "y") (inc %)))
=> "x\n6\ny\n"
(with-out-str
(-> (+ 1 2)
(within (println %))
inc
(within (println %))
inc))
=> "3\n4\n"
(-> (+ 1 2)
(within (println %))
inc
(within (println %))
inc)
=> 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment