Last active
February 9, 2020 18:31
-
-
Save arademaker/50aa74e490bf2160547cb212c9a1bf05 to your computer and use it in GitHub Desktop.
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-open-files (args &rest body) | |
(let ((res `(progn ,@body))) | |
(reduce (lambda (acc e) `(with-open-file (,@e) ,acc)) args | |
:initial-value res))) | |
(defmacro with-open-files-1 (args &rest body) | |
(let ((res `(progn ,@body))) | |
(dolist (a (reverse args) res) | |
(setf res `(with-open-file (,@a) | |
,res))))) | |
;; testing | |
(with-open-files ((in filename-in :direction :input) | |
(log filename-log :direction :ouput :if-exists :append) | |
(out filename-out :direction :ouput :if-exists :supersede)) | |
(format out "ads") | |
(format out "ads")) | |
;; I want | |
(with-open-file (out filename-out :direction :ouput :if-exists | |
:supersede) | |
(with-open-file (log filename-log :direction :ouput :if-exists | |
:append) | |
(with-open-file (in filename-in :direction :input) | |
(format out "ads") | |
(format out "ads"))))) | |
;; I got | |
(with-open-file (out filename-out :direction :ouput :if-exists | |
:supersede) | |
(with-open-file (log filename-log :direction :ouput :if-exists | |
:append) | |
(with-open-file (in filename-in :direction :input) | |
(progn (format out "ads") | |
(format out "ads"))))) |
There is no need to distinguish having one spec left from having many. Only the bottom case is important. One can simplify the macro to:
(defmacro with-open-files (args &body body)
(if args
`(with-open-file ,(first args)
(with-open-files
,(rest args) ,@body))
`(progn ,@body)))
Btw the nest macro is designed as a more general solution to this situation. I prefer your solution though.
https://github.com/ruricolist/serapeum/blob/master/REFERENCE.md#nest-rest-things
Indeed, thank you for the improvement. It would bd nice to have it in serapeum!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My final version is