with and within
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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